HTTPClient和URLConnection核心區別分析

首先:在 JDK 的 java.net 包中已經提供了訪問 HTTP 協議的基本功能:HttpURLConnection。但是對於大部分應用程序來說,JDK 庫本身提供的功能還不夠豐富和靈活。
在Android中,androidSDK中集成了Apache的HttpClient模塊,用來提供高效的、最新的、功能豐富的支持 HTTP 協議工具包,並且它支持 HTTP 協議最新的版本和建議。使用HttpClient可以快速開發出功能強大的Http程序。
其次:HttpClient是個很不錯的開源框架,封裝了訪問http的請求頭,參數,內容體,響應等等,

HttpURLConnection是java的標準類,什麼都沒封裝,用起來太原始,不方便,比如重訪問的自定義,以及一些高級功能等。

HttpClient就是一個增強版的HttpURLConnection,HttpURLConnection可以做的事情HttpClient全部可以做;HttpURLConnection沒有提供的有些功能,HttpClient也提供了,但它只是關注於如何發送請求、接收響應,以及管理HTTP連接。

使用HttpClient發送請求、接收響應很簡單,只要如下幾步即可:
1.創建HttpClient對象。
2.如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
3.如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。
4.調用HttpClient對象的execute(HttpUriRequest request)發送請求,執行該方法返回一個HttpResponse。
5.調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。

具體對比如下:HTTPClient

String url = "http://192.168.1.100:8080"; 
public HttpClientServer(){ } 
public String doGet(String username,String password){ 
   String getUrl = urlAddress + "?username="+username+"&password="+password; 
   HttpGet httpGet = new HttpGet(getUrl); 
   HttpParams hp = httpGet.getParams(); 
   hp.getParameter("true"); 
  //httpGet.setp 
  HttpClient hc = new DefaultHttpClient(); 
     try { 
     HttpResponse ht = hc.execute(httpGet); 
     if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 
      HttpEntity he = ht.getEntity(); 
      InputStream is = he.getContent(); 
      BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
      String response = ""; 
      String readLine = null; 
      while((readLine =br.readLine()) != null){ 
       //response = br.readLine(); 
      response = response + readLine; 
   } 
   is.close(); 
   br.close(); 
//String str = EntityUtils.toString(he); 
    return response; 
}else{ 
    return "error"; 
  } 
} catch (ClientProtocolException e) { 
   e.printStackTrace(); 
   return "exception"; 
} catch (IOException e) { 
   e.printStackTrace(); 
  return "exception"; 
  } 
} 
 public String doPost(String username,String password){ 
     //String getUrl = urlAddress + "?username="+username+"&password="+password; 
     HttpPost httpPost = new HttpPost(urlAddress); 
     List params = new ArrayList(); 
     NameValuePair pair1 = new BasicNameValuePair("username", username); 
     NameValuePair pair2 = new BasicNameValuePair("password", password); 
     params.add(pair1); 
     params.add(pair2); 
     HttpEntity he; 
     try { 
         he = new UrlEncodedFormEntity(params, "gbk"); 
         httpPost.setEntity(he); 
      } catch (UnsupportedEncodingException e1) { 
        e1.printStackTrace(); 
  } 

  HttpClient hc = new DefaultHttpClient(); 
      try { 
        HttpResponse ht = hc.execute(httpPost); 
       //連接成功 
       if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 
       HttpEntity het = ht.getEntity(); 
       InputStream is = het.getContent(); 
       BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
       String response = ""; 
       String readLine = null; 
       while((readLine =br.readLine()) != null){ 
       //response = br.readLine(); 
      response = response + readLine; 
    } 
    is.close(); 
    br.close(); 
  //String str = EntityUtils.toString(he); 
     return response; 
  }else{ 
     return "error"; 
  } 
  } catch (ClientProtocolException e) { 
    e.printStackTrace(); 
    return "exception"; 
  } catch (IOException e) { 
    e.printStackTrace(); 
    return "exception"; 
   } 
}
HttpURLConnection:
String url = "http://192.168.1.100:8080"; 
URL url; 
HttpURLConnection uRLConnection; 
public UrlConnectionToServer(){ }
//向服務器發送get請求
public String doGet(String username,String password){ 
String getUrl = urlAddress + "?username="+username+"&password="+password; 
try { 
url = new URL(getUrl); 
uRLConnection = (HttpURLConnection)url.openConnection(); 
InputStream is = uRLConnection.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
String response = ""; 
String readLine = null; 
while((readLine =br.readLine()) != null){ 
//response = br.readLine(); 
response = response + readLine; 
} 
is.close(); 
br.close(); 
uRLConnection.disconnect(); 
return response; 
} catch (MalformedURLException e) { 
e.printStackTrace(); 
returnnull; 
} catch (IOException e) { 
e.printStackTrace(); 
returnnull; 
} 
} 


//向服務器發送post請求

public String doPost(String username,String password){ 
try { 
url = new URL(urlAddress); 
uRLConnection = (HttpURLConnection)url.openConnection(); 
uRLConnection.setDoInput(true); 
uRLConnection.setDoOutput(true); 
uRLConnection.setRequestMethod("POST"); 
uRLConnection.setUseCaches(false); 
uRLConnection.setInstanceFollowRedirects(false); 
uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
uRLConnection.connect(); 
DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream()); 
String content = "username="+username+"&password="+password; 
out.writeBytes(content); 
out.flush(); 
out.close(); 
InputStream is = uRLConnection.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
String response = ""; 
String readLine = null; 
while((readLine =br.readLine()) != null){ 
//response = br.readLine(); 
response = response + readLine; 
} 
is.close(); 
br.close(); 
uRLConnection.disconnect(); 
return response; 
} catch (MalformedURLException e) { 
e.printStackTrace(); 
returnnull; 
} catch (IOException e) { 
  e.printStackTrace(); 
  returnnull; 
 } 
}
客戶端操作:
String url = "http://192.168.1.102:8080"; 
String body = 
getContent(urlAddress); 
JSONArray array = new JSONArray(body); 
for(int i=0;i<array.length();i++) 
{ 
obj = array.getJSONObject(i); 
sb.append("用戶名:").append(obj.getString("username")).append("\t"); 
sb.append("密碼:").append(obj.getString("password")).append("\n"); 

HashMap<String, Object> map = new HashMap<String, Object>(); 
try { 
userName = obj.getString("username"); 
passWord = obj.getString("password"); 
} catch (JSONException e) { 
e.printStackTrace(); 
} 
map.put("username", userName); 
map.put("password", passWord); 
listItem.add(map); 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 
if(sb!=null) 
{ 
showResult.setText("用戶名和密碼信息:"); 
showResult.setTextSize(20); 
} else
extracted(); 
//設置adapter 
SimpleAdapter simple = new SimpleAdapter(this,listItem, 
android.R.layout.simple_list_item_2, 
new String[]{"username","password"}, 
newint[]{android.R.id.text1,android.R.id.text2}); 
listResult.setAdapter(simple); 

listResult.setOnItemClickListener(new OnItemClickListener() { 
@Override 
publicvoid onItemClick(AdapterView<?> parent, View view, 
int position, long id) { 
int positionId = (int) (id+1); 
Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show(); 
} 
}); 
} 
privatevoid extracted() { 
showResult.setText("沒有有效的數據!"); 
} 
//和服務器連接 
private String getContent(String url)throws Exception{ 
StringBuilder sb = new StringBuilder(); 
HttpClient client =new DefaultHttpClient(); 
HttpParams httpParams =client.getParams(); 
HttpConnectionParams.setConnectionTimeout(httpParams, 3000); 
HttpConnectionParams.setSoTimeout(httpParams, 5000); 
HttpResponse response = client.execute(new HttpGet(url)); 
HttpEntity entity =response.getEntity(); 
if(entity !=null){ 
BufferedReader reader = new BufferedReader(new InputStreamReader 
(entity.getContent(),"UTF-8"),8192); 
String line =null; 
while ((line= reader.readLine())!=null){ 
sb.append(line +"\n"); 
} 
reader.close(); 
} 
return sb.toString(); 
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章