Skip to content

Android:HttpClient

Permission

우선, 아래와 같이 권한을 추가해야 한다.

<uses-permission android:name="android.permission.INTERNET" />

HttpClient Timeout 처리하는 방법

HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);

Response Status code 획득방법

아래와 같이 하면 HTTP상태코드를 획득할 수 있다.

// ...
HttpResponse responseGet = client.execute(get);
response.getStatusLine().getStatusCode()

안드로이드 플랫폼에서 HTTP GET/POST/Multipart POST 요청 처리하기

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

References


  1. Android_http_client_librarys.pdf