Calling web API and Receive return value in Android

后端 未结 4 1402
花落未央
花落未央 2021-01-03 15:45

I\'ve googled for that topics and don\'t get any useful information.

I want to use Web API in my android projects, but don\'t know how to call them from android or j

相关标签:
4条回答
  • 2021-01-03 16:19
    public class JsonWebServiceCall {
    // HttpURLConnection method to get JSON data from Webservice
    public static String GetJsonString(String mUpdateUrl) {
    
        String result=null;
        try {
    
            URL url = new URL(mUpdateUrl);
    
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            StringBuilder sb = new StringBuilder();
    
            con.setAllowUserInteraction(false);
            con.setInstanceFollowRedirects(true);
            // con.setRequestMethod("POST");
            con.connect();
             if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // BufferedReader bufferedReader = new BufferedReader(new
            // InputStreamReader(con.getInputStream()));
            try {
                InputStream in = new BufferedInputStream(con.getInputStream());
    
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(in));
    
                String json;
    
                while ((json = bufferedReader.readLine()) != null) {
                    System.out.println(mUpdateUrl + "kkkkkkkkk------" + json);
                    sb.append(json + "\n");
                }
            } catch (Exception e) {
    
                e.printStackTrace();
    
            }
            Log.i("json", "===" + sb.toString().trim());
            result=sb.toString().trim();}
             else{
                 result=null;
             }
     return result;
        } catch (Exception e) {
            return null;
        }
    
    }
    
    // HttpURLConnection method to get JSON data from Webservice
    public static String PostJsonString(String mUpdateUrl, String webserviceurl) {
    
        // BufferedReader bufferedReader = null;
        try {
    
            String urlParameters = mUpdateUrl;
            URL url = new URL(webserviceurl);
            URLConnection conn = url.openConnection();
            StringBuilder sb = new StringBuilder();
            conn.setDoOutput(true);
    
            OutputStreamWriter writer = new OutputStreamWriter(
                    conn.getOutputStream());
    
            writer.write(urlParameters);
            writer.flush();
    
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
    
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                sb.append(line + "\n");
            }
            writer.close();
            reader.close();
            return sb.toString().trim();
        } catch (Exception e) {
            return null;
        }
    
    }
    

    Asynchtask..........

    public static class AsyncCriticalMessage extends AsyncTask<Void, Void, Void> {
    
        String result = null;
        CriticalMessageServiceSuccess criticalMessageServiceSuccess = null;
    
        public AsyncCriticalMessage(CriticalMessageServiceSuccess criticalMessageServiceSuccess) {
            this.criticalMessageServiceSuccess = criticalMessageServiceSuccess;
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            result = JsonWebServiceCall.GetJsonString(Globals.FORCEUPDATE_MESSAGE_SERVICE_URL);
            return null;
        }
    
        @Override
        protected void onPostExecute(Void Result) {
            super.onPostExecute(Result);
    
            criticalMessageServiceSuccess.onSuccess(result);
        }
    }
     AsyncCriticalMessage asyncCriticalMessage=new AsyncCriticalMessage(this);
        asyncCriticalMessage.execute();
    
    0 讨论(0)
  • 2021-01-03 16:20

    A simple Async call would do the thing for you.:

    MainActivity.java

    new YourAsync(){
    
                protected void onPostExecute(Object[] result) {
    
                    String response = result[1].toString();
                    try{
                    JSONObject jsonObject=(new JSONObject(jsonResult)).getJSONObject("data"); //Parsing json object named 'data'
                    yourTextView.setText(jsonObject.getString("uname")); 
            }.execute(YourURL);
    

    YourAsync.java

    public class YourAsync extends AsyncTask<String, Integer, Object[]> {
    
        @Override
        protected Object[] doInBackground(String... params) {
            // TODO Auto-generated method stub
    
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0].toString());
            Log.d("http client post set","");
    
            try{
                HttpResponse response = httpclient.execute(httppost);
                Log.d("YourAsync","Executed");
                return new Object[]{response, new BasicResponseHandler().handleResponse(response)};
            }catch(Exception e){
                Log.d("" + e, "");
            }
            return new Object[0];
        }
    
    0 讨论(0)
  • 2021-01-03 16:23

    Since I just want to display the the User ID return from the API, below the solution is work for me.

    public class MainActivity extends Activity {
    
        public static TextView txtUserid;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
                        Button btnUserid = (Button) findViewById(R.id.btnUserid);
            btnUserid.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    new UserNameToId().execute("https://uhunt.onlinejudge.org/api/uname2uid/almaruf");
                }
            });
        }
    
        protected class UserNameToId extends AsyncTask<String, Void, String> {
            @Override
            public String doInBackground(String... url) {
    
                try {
                    URL Url = new URL(url[0]);
                    URLConnection urlConnection = Url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String str = "";
                    str = bufferedReader.readLine();
                    return str;
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                return null;
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                txtUserid = (TextView) findViewById(R.id.txtUserId);
                txtUserid.setText(result);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 16:37

    You need AsyncTask to do the networking transmission and receiving using appropriate Connection classes, and finally have it return the value to the main UI thread via onPostExecute(). I am really not sure what is the sticking point that prevents you proceeding normally.

    0 讨论(0)
提交回复
热议问题