3

this code is ok for get data from server but if my API is POST Method how to pass params to server by POSt Request and fetch data. code is here, please let me know

    public  class GetTripTeportData extends AsyncTask<String, Integer,String> {
    @Override
    protected void onPreExecute() {...}

    @Override
    protected String doInBackground(String... params) {
        String responseBodyText = null;
        OkHttpClient client = new OkHttpClient();
        try {
            Request request = new Request.Builder().url(excelApi).build();
            Response response = null;
            response = client.newCall(request).execute();//.....

                responseBodyText = response.body().string();
                JSONObject resultData = new JSONObject(responseBodyText);
                JSONArray itemArray = resultData.getJSONArray("data");
                for (int i=0; i<itemArray.length();i++){
                    JSONObject jobject = itemArray.getJSONObject(i);
                    String iduser = jobject.getString("id");
                    String vehicleno = jobject.getString("vehicleno");
                    String startdate = jobject.getString("startdate");
                    allList.add(new ExcelReportAdminResponse(iduser,vehicleno,startdate));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
        return responseBodyText;
    }

    @Override
    protected void onPostExecute(String s) {......}
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Parveen Haade
  • 76
  • 1
  • 13

2 Answers2

0

To post data with default http client with async task you can do as below:

First create network utility class as below:

public class NetworkUtilities {

    public static String postData(String Url, String message ){
        try {
            URL url = new URL(Url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000); /*milliseconds*/
            conn.setConnectTimeout(15000); /* milliseconds */
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setFixedLengthStreamingMode(message.getBytes().length);
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            conn.connect();
            OutputStream os = new BufferedOutputStream(conn.getOutputStream());
            os.write(message.getBytes());
            os.flush();
            InputStream is = conn.getInputStream();
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
        catch (Exception e){
            Log.e("Exception: " , e.toString());
        }
        finally {
            // os.close();
            //is.close();
            //conn.disconnect();
        }
        return "";
    }

}

Then write async task to call that postData() method from NetworkUtilities class as below:

private class PostDataAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            return NetworkUtilities.postData(params[0], params[1]);
        }

        @Override
        protected void onPostExecute(String result) {
            Log.e("Data response: ", result);
        }

        @Override
        protected void onPreExecute() {
            // TODO: Loader and stuff to add later here.
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

Then to call that async task means to call api do as below:

String message = "";
try {
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("user_id", session.getSession());
    message = jsonBody.toString();
} catch (Exception e) {
    Log.e("JSON error: ", e.toString());
}

PostDataAsync postData = new PostDataAsync();
postData.execute("YOUR_POST_API_URL_HERE", message);

By using this way you can be able to post data with async task.

android
  • 2,942
  • 1
  • 15
  • 20
0

For POST call with JSON body

final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

RequestBody body = RequestBody.create(JSON, /*YOUR JSON REQUEST*/ jsonString);
Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();

try {
   Response response = client.newCall(request).execute();
} catch(IOException io){
  // do something
}
Hussain
  • 1,243
  • 12
  • 21