Android HttpClient

    使用Apache提供的HttpClient接口進行HTTP操做。java

    GET方法:android

// http地址 
String httpUrl = ;
//HttpGet鏈接對象 
HttpGet httpRequest = new HttpGet(httpUrl);
//取得HttpClient對象 
HttpClient httpclient = new DefaultHttpClient();
//請求HttpClient,取得HttpResponse 
HttpResponse httpResponse = httpclient.execute(httpRequest);
//請求成功 
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得返回的字符串 
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println(strResult); 
}else{
System.out.println("請求錯誤!");
}

    POST方法:jsp

// http地址 
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//HttpPost鏈接對象 
HttpPost httpRequest = new HttpPost(httpUrl);
//使用NameValuePair來保存要傳遞的Post參數 
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加要傳遞的參數 
params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
//設置字符集 
HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
//請求httpRequest 
httpRequest.setEntity(httpentity);
//取得默認的HttpClient 
HttpClient httpclient = new DefaultHttpClient();
//取得HttpResponse 
HttpResponse httpResponse = httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示鏈接成功 
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得返回的字符串 
String strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println(strResult); 
}else{
System.out.println("請求錯誤!");
}
相關文章
相關標籤/搜索