Home > Back-end >  How can I make an http post request using java on android
How can I make an http post request using java on android

Time:06-21

How can I hit an api post end point using java and pass a body as a json data ?

I found this code on the android docs but I don't know how to pass the request body

 URL url = new URL("http://www.android.com/");
 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
 try {
   urlConnection.setDoOutput(true);
   urlConnection.setChunkedStreamingMode(0);
   OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
   writeStream(out);

   InputStream in = new BufferedInputStream(urlConnection.getInputStream());
   readStream(in);
} finally {
   urlConnection.disconnect();
}

CodePudding user response:

I am kotlin Guy but this is how I have done post request in java

new Thread(() -> {
    try {
        URL url = new URL("http://www.android.com/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        DataOutputStream requestWriter = new DataOutputStream(connection.getOutputStream());
        requestWriter.writeBytes(JsonBodyObject.toString());
        requestWriter.close();
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseData = responseReader.readLine();
        activity.runOnUiThread(() -> {
            try {
                JSONObject json = new JSONObject(responseData);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        });
        responseReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

CodePudding user response:

I use http client and it goes really well, (unless you send a delete call with body).

Here you have all the info you need to import it and get it done.

How to import "HttpClient" to Eclipse?

With this you can get your call running if you have problems building the thing with httpClient, send your code in this question and i will try to help.

  • Related