0

Is there a recommended way of doing post request in android? because before I use HttpPost and HttpClient for executing post request but these classes are now deprecated in API level 22.

hardartcore
  • 16,886
  • 12
  • 75
  • 101
Earwin delos Santos
  • 2,965
  • 7
  • 20
  • 29

3 Answers3

0

You can use HttpURLConnection

 public  String makeRequest(String pageURL, String params)
{
    String result = null;
    String finalURL =pageURL;
    Logger.i("postURL", finalURL);
    Logger.i("data", params);
    try {
        URL url = new URL(finalURL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestProperty("Accept", "application/json");
        OutputStream os = urlConnection.getOutputStream();
        os.write(params.getBytes("UTF-8"));
        os.close();
        int HttpResultCode =urlConnection.getResponseCode();
        if(HttpResultCode ==HttpURLConnection.HTTP_OK){
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            result = convertStreamToString(in);
            Logger.i("API POST RESPONSE",result);
        }else{
            Logger.e("Error in response ", "HTTP Error Code "+HttpResultCode +" : "+urlConnection.getResponseMessage());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Then converting your stream to string

 private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

Create your JSON

JSONObject j=new JSONObject();
        try {
            j.put("name","hello");
            j.put("email","hello@gmail.com");
        } catch (JSONException e) {
            e.printStackTrace();
        }

  //Call the method
        makeRequest("www.url.com",j.toString());
WISHY
  • 11,067
  • 25
  • 105
  • 197
0

Yeah, they are deprecated. You can use Volley which is recommended by Google Dev.

Volley offers the following benefits: Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.

Volley is very easy to use:

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
@Override
public void onResponse(String response) {
    // Display the first 500 characters of the response string.
    mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
    mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
0

Just to show another possible library that could help you: OkHttp

With an example post from their webseite:

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

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

Or Retrofit.

You basically create an interface with annotations about the rest API and parameters you are calling, and can receive the parsed json model like this:

public interface MyService {
    @POST("/api")
    void createTask(@Body CustomObject o, Callback<CustomObject > cb);
}

You can set them both also up together, here is a guide that helped me a lot: https://futurestud.io/blog/retrofit-getting-started-and-android-client/

Even though this is not the official way recommended in the google docs, these are nice libraries, worth taking a look into.

Maximosaic
  • 604
  • 6
  • 14