Search code examples
javaandroidhttpurlconnection

Ho do I know if a post request has been successful


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;
    }
}

Solution

  • 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