HTTPClient和URLConnection核心區別分析
在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();
}
------------------------------------------------------
private void HttpPostData() {
try {
HttpClient httpclient = new DefaultHttpClient();
String uri = "http://www.yourweb.com";
HttpPost httppost = new HttpPost(uri);
//新增http頭資訊
httppost.addHeader("Authorization", "your token"); //認證token
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("User-Agent", "imgfornote");
//http post的json資料格式: {"name": "your name","parentId": "id_of_parent"}
JSONObject obj = new JSONObject();
obj.put("name", "your name");
obj.put("parentId", "your parentid");
httppost.setEntity(new StringEntity(obj.toString()));
HttpResponse response;
response = httpclient.execute(httppost);
//檢驗狀態碼,如果成功接收資料
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}
obj = new JSONObject(rev);
String id = obj.getString("id");
String version = obj.getString("version");
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (Exception e) {
}
}
----------------------------------------
private class httpPost extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... args) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String url = args[0];
String json=args[1];
JSONObject JSONResponse = null;
InputStream contentStream = null;
String resultString = "";
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(json);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
for (int i=0;i<httppost.getAllHeaders().length;i++) {
Log.v("set header", httppost.getAllHeaders()[i].getValue());
}
HttpResponse response = httpclient.execute(httppost);
// Do some checks to make sure that the request was processed properly
Header[] headers = response.getAllHeaders();
HttpEntity entity = response.getEntity();
contentStream = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
contentStream.close();
resultString = sb.toString();
}catch(Exception e){
e.printStackTrace();
}
Log.v("li", resultString);
return new JSONObject();
}
}