How to do a POST using the HttpUrlConnection class of Android?

1

I need to send a JSON generated in the Android application to a web application. Using the HttpUrlConnection class I made 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 JSON , except that the web application receives nothing. Using the RESTClient plugin of Firefox I ran a test, put the same URL and% generated as%. When you run the JSON method, the record has been correctly included.

Why is the POST application not sending the request correctly?

    
asked by anonymous 24.08.2015 / 21:31

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 you can not send

    
25.08.2015 / 14:04