Android HttpClient 기본 사용 방법

2381 단어 httpclientgetpost
HttpClient를 사용하여 GET 또는 POST 요청을 시작하는 방법만 설명합니다.
 
GET 모드
 
//      List,      URL  
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "  "));
params.add(new BasicNameValuePair("param2", "value2"));

//     
String param = URLEncodedUtils.format(params, "UTF-8");

//baseUrl			
String baseUrl = "http://ubs.free4lab.com/php/method.php";

// URL     
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);
			
HttpClient httpClient = new DefaultHttpClient();

try {
    HttpResponse response = httpClient.execute(getMethod); //  GET  

    Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //     
    Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//         
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
 
 
 
POST 모드
 
// GET    ,      List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post  "));
params.add(new BasicNameValuePair("param2", "     "));
			
try {
    HttpPost postMethod = new HttpPost(baseUrl);
    postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //     POST Entity 
				
    HttpResponse response = httpClient.execute(postMethod); //  POST  
    Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //     
    Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //      
				
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

좋은 웹페이지 즐겨찾기