Gustavo Serna Gustavo Serna - 2 months ago 5x
Android Question

Android httpUrlConnection sending and receiving data

I am aware that here in stackoverflow are plenty of questions related to mine, but I cant understand 100% to their explanations of how to send and receive data from a web server using httpUrlConnection.

I used to do it with httpClient and I used the following code:

Here is my class httpClient:

public class httpHandler {
public String post(String posturl){


HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);

HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();

String text = EntityUtils.toString(ent);

return text;

}catch(Exception e){
return "error";


and then I used to send and receive the data like this:

String responseLikeCuenta =;

It was as simple as that but now with the httpUrlConnection I cant understand how to do it, and when I read the tutorials I see lots of code just for sending one string. Is there a simpler way to do it?

Is there a way to do it inside the onCreate?


As far as I know, most Android programmers use OkHttp library for internet connection instead of HttpUrlConnection. The reason is that this is quite an old class from Java package and it was not meant for mobile when it was made. As far as I understand, OkHttp actually uses HttpUrlConnection under the hood, but alongside some notable improvements for mobile devices, e.g.:

None of this should bother you if you do not wish to know more about it, but those are just some of the reasons to use it. The biggest reason for you may be the ease of usage. OkHttp has great docs and you'll understand how to use it in a matter of seconds.