Answer the question
In order to leave comments, you need to log in
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
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¶m2=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;
https://github.com/kevinsawicki/http-request - I recommend the library, uses HttpURLConnection, simple and convenient. All with examples at the link
There is a very good lib https://code.google.com/p/android-query/ that allows you not only to send HTTP requests.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question