How do I use the AndroidHttpClient
as an HTTP client to connect to a remote server? I have not been able to find good examples in the documentation nor on the internet.
Asked
Active
Viewed 1.6e+01k times
76

Ry-
- 218,210
- 55
- 464
- 476

user538626
- 911
- 2
- 11
- 15
-
3This is actually a useful question. There's not a lot of examples of how to use AndroidHttpClient. Maybe the question should be more specific. – Dave Jensen Aug 03 '13 at 19:24
-
3I updated this to make it a real question. Please re-open it because, as you can see, this has been a useful question to many people. – Dave Jensen Apr 10 '14 at 21:19
-
Are we going to re-open this or what? – Dave Jensen Apr 10 '14 at 21:22
-
1Why? That makes zero sense to me. Sometimes SO completely baffles & frustrates me. – Dave Jensen Apr 14 '14 at 05:27
-
2I reached here by googling *android http client example*. It seems that the above average programmer's questions are real. – Mohammed H Jun 04 '14 at 08:24
3 Answers
98
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

Marc Gravell
- 1,026,079
- 266
- 2,566
- 2,900

Cristian
- 198,401
- 62
- 356
- 264
-
11your lmgtfy attracted lots of "offensive" flags. I strongly recommend not doing that. – Marc Gravell Dec 16 '10 at 09:37
-
2
-
To make this work with GZIP, chunked stream etc, use the HttpClient and entity.writeTo() instead. – Asmo Soinio Mar 22 '11 at 10:43
-
-
6Honeycomb and newer will throw a `NetworkOnMainThreadException` if you try to do this without using [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html). – JaKXz Jul 18 '13 at 04:46
-
can you update this ? or this method still valid in 2014 ? or at least give some links to actual methods ? – Francisco Corrales Morales Apr 06 '14 at 02:07
-
This is still valid, but now there are libraries that do this for you. For instance https://github.com/kevinsawicki/http-request – Cristian Apr 07 '14 at 15:53
-
My app stops at the 'response = httpclient.execute(httpget);' line, eventually times out and goes to 'catch'. its simply hitting a php fiel that returns data in json format. – Fearghal Mar 30 '15 at 12:55
-
1HttpClient is now a legacy. You better use OkHttp since Android SDK 23 Marshmallow. – lomza Jan 08 '16 at 13:45
-
In order to use this in API > 22 add this to app build.gradle `android{ useLibrary 'org.apache.http.legacy' }` – serj Jul 01 '16 at 09:49
2
You can use like this:
public static String executeHttpPost1(String url,
HashMap<String, String> postParameters) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpClient client = getNewHttpClient();
try{
request = new HttpPost(url);
}
catch(Exception e){
e.printStackTrace();
}
if(postParameters!=null && postParameters.isEmpty()==false){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request,localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, ""+statusCode);
Log.i(TAG, "------------------------------------------------");
try{
InputStream in = (InputStream) entity.getContent();
//Header contentEncoding = Response.getFirstHeader("Content-Encoding");
/*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
response = str.toString();
Log.i(TAG, "response"+response);
}
catch(IllegalStateException exc){
exc.printStackTrace();
}
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+response);
}
finally {
}
return response;
}

gustavohenke
- 40,997
- 14
- 121
- 129

nikki
- 3,248
- 3
- 24
- 29
1
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

Andrew Barber
- 39,603
- 20
- 94
- 123

9android
- 31
- 4
-
Welcome to Stack Overflow! Thanks for posting your answer! Please be sure to read the [FAQ on Self-Promotion](http://stackoverflow.com/faq#promotion) carefully. Also note that it is *required* that you post a disclaimer every time you link to your own site/product. – Andrew Barber Mar 15 '13 at 03:48