W
W
wolfak2016-01-13 18:32:51
Java
wolfak, 2016-01-13 18:32:51

How to send a POST request using HttpURLConnection?

Good evening. I started to understand programming for android and found many detailed instructions for sending a POST request to a php server using HttpClient, but then I found out that it was outdated and no longer supported by the latest SDK that I have installed.
After that, I learned that I should use HttpURLConnection, but I did not find information on how to make POST or GET requests using it and process the response from the server.
I hope for your help, preferably with detailed examples. Thanks a lot.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
T
tepexob, 2016-01-13
@wolfak

Something like this at least. And there you will process what and how it is required and necessary.

String myURL = "http://myserver.com";
String params = "param1=1&param2=XXX";
byte[] data = null;
InputStream is = null;

try {
    URL url = new URL(myURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
    OutputStream os = conn.getOutputStream();
    data = params.getBytes("UTF-8");
    os.write(data);
    data = null;

    conn.connect();
    int responseCode= conn.getResponseCode();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    is = conn.getInputStream();

    byte[] buffer = new byte[8192]; // Такого вот размера буфер
    // Далее, например, вот так читаем ответ
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        baos.write(buffer, 0, bytesRead);
    }
    data = baos.toByteArray();
} catch (Exception e) {
} finally {
    try {
        if (is != null)
            is.close();
    } catch (Exception ex) {}
}
return data;

There is no particular difference from HttpClient.

C
coden55, 2016-01-13
@coden55

https://github.com/kevinsawicki/http-request - I recommend the library, uses HttpURLConnection, simple and convenient. All with examples at the link

L
larry-troy, 2016-01-17
@larry-troy

There is a very good lib https://code.google.com/p/android-query/ that allows you not only to send HTTP requests.

C
cherry1, 2017-06-12
@cherry1

and what is written in the parameters (parammetrs)? Login and password?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question