How to make a POST using the Httpurlconnection class of Android?

Asked

Viewed 6,018 times

1

I need to send a JSON generated in the application Android for a web application. Using the class HttpUrlConnection I did the following encoding:

private void sendPost(String url, String postParams) {
    try {
        URL obj = new URL(url);
        conn = (HttpURLConnection) obj.openConnection();

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
        conn.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
}

When running, the system correctly sends the method URL and the JSON, but the web application does not receive anything. Using the plugin RESTClient I did a test, put the same URL and the JSON generated. When executing the method POST the record was included correctly.

Why the application Android is not sending the request correctly?

1 answer

1


URL obj = new URL(url);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();  //abre conexao

    connection.setRequestMethod("POST"); //fala que quer um post

    connection.setRequestProperty("Content-type", "application/json"); //fala o que vai mandar

    connection.setDoOutput(true); //fala que voce vai enviar algo


    PrintStream printStream = new PrintStream(connection.getOutputStream());
    printStream.println(json); //seta o que voce vai enviar

    connection.connect(); //envia para o servidor

    String jsonDeResposta = new Scanner(connection.getInputStream()).next(); //pega resposta

It is very important to bring the answer in this class, otherwise Voce cannot send

  • Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.