-2

I am making a post request to this endpoint http://httpbin.org/post which should return the post I make, which would be String data = "something to post"; but I don't know if the post request has been successful. How can I find out?

Here the code I am using:

public class Post extends AsyncTask <String, String, String>{

    @Override
    protected String doInBackground(String... strings) {
        String urlString = "http://httpbin.org/post"; // URL to call

        Log.d("Blyat", urlString);

        String data = "something to post"; //data to post
        OutputStream out = null;

        try {
            URL url = new URL(urlString);

            Log.d("Post", String.valueOf(url));

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            out = new BufferedOutputStream(urlConnection.getOutputStream());

            Log.d("Post", String.valueOf(out));

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();

            urlConnection.connect();
            Log.d("Post", String.valueOf(urlConnection));

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        String algo = "blure";
        return algo;
    }
}
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • 1
    I don't think this is a good implementation. You can tell the success or failure by looking at HTTP response codes from the server. I would recommend a client library written by someone else. – duffymo Aug 06 '18 at 19:32
  • https://en.wikipedia.org/wiki/List_of_HTTP_status_codes – Elroy Jetson Aug 06 '18 at 19:33
  • https://stackoverflow.com/questions/6467848/how-to-get-http-response-code-for-a-url-in-java – CodeSmith Aug 06 '18 at 21:37

1 Answers1

1

After writing on a OutputStream from a URLConnection you must then check for the status code from the connection object.

int statusCode = connection.getStatusCode();

if success ( == 200) then you can read the response by getting it from the InputStream of the Connection.

BufferedReader reader = new BufferedReader(connection.getInputStream());

From the response you will usually convert to string such:

        is = connection.getInputStream();
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        String response =  writer.toString();// have the body from response as String
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167