Android:HttpClient
lastmod 2018-08-17created 2016-11-244 edits
Permission
First, add the permission as follows.
How to handle HttpClient Timeout
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
How to get the Response Status code
You can get the HTTP status code as follows.
Handling HTTP GET/POST/Multipart POST requests on the Android platform
HTTP Get
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// 결과를 처리합니다.
Log.i("RESPONSE", EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
HTTP POST
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.google.com";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "kris"));
params.add(new BasicNameValuePair("pass", "xyz"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
HTTP POST (File Attached)
File file = new File("path/to/your/file.txt");
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.google.com";
HttpPost post = new HttpPost(postURL);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("myFile", bin);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
See also
Favorite site
- [Recommended] HTTP client libraries for Android 1
- How to send an HTTP post
References
-
Android_http_client_librarys.pdf ↩
Pages that link here