Calling web API and Receive return value in Android

后端 未结 4 1424
花落未央
花落未央 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: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 {
    
        @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];
        }
    

提交回复
热议问题