android系统提供了url通信,Android两种HTTP通信,HttpURLConnection和HttpClient
Android系統中主要提供了兩種方式來進行HTTP通信,HttpURLConnection和HttpClient,幾乎在任何項目的代碼中我們都能看到這兩個類的身影,使用率非常高。
不過HttpURLConnection和HttpClient的用法還是稍微有些復雜的,如果不進行適當封裝的話,很容易就會寫出不少重復代碼。于是乎,一些Android網絡通信框架也就應運而生,比如說AsyncHttpClient,它把HTTP所有的通信細節全部封裝在了內部,我們只需要簡單調用幾行代碼就可以完成通信操作了。再比如Universal-Image-Loader,它使得在界面上顯示網絡圖片的操作變得極度簡單,開發者不用關心如何從網絡上獲取圖片,也不用關心開啟線程、回收圖片資源等細節,Universal-Image-Loader已經把一切都做好了。這里簡單介紹下HttpURLConnection和HttpClient的使用。至于框架后面會研究后,再介紹
HttpClient的get使用
HttpClient?mClient;?//http客戶端
public?static?HttpEntity?getEntity(String?uri,ArrayList?params,int?method)?throws????ClientProtocolException,?IOException{
mClient=new?DefaultHttpClient();
HttpUriRequest?request=null;
switch?(method)?{
case?HTTP_GET://get請求
StringBuilder?sb=new?StringBuilder(uri);
//判斷設置參數為不為空
if(null!=params&&!params.isEmpty()){
sb.append("?");
//設置配置參數
for?(BasicNameValuePair?param?:?params)?{
sb.append(param.getName()).append("=")
.append(URLEncoder.encode(param.getValue(),?"utf-8")).append("&");
}
sb.deleteCharAt(sb.length()-1);????//刪除多余的?&
}
HttpGet?get=new?HttpGet(sb.toString());????//發送get請求
request=get;
break;
}
//cookie緩存
HttpClientParams.setCookiePolicy(mClient.getParams(),?CookiePolicy.BROWSER_COMPATIBILITY);
//連接時間
mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,?5000);
//設置請求超時時間
mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,?5000);
//執行請求?獲得響應
HttpResponse?response?=?mClient.execute(request);
if(response.getStatusLine().getStatusCode()==200){????//如果成功?返回HttpEntity?對象
return?response.getEntity();
}
return?null;
}
HttpURLConnection的post使用 post是 表單方式請求的
URL?url?=new?URL(actionUrl);
HttpURLConnection?con=(HttpURLConnection)url.openConnection();
con.setReadTimeout(10?*?1000);????????//讀數請求時間
con.setConnectTimeout(10?*?1000);????//連接超時
/*?允許Input、Output,不使用Cache?*/
con.setDoInput(true);????//以后就可以使用conn.getInputStream().read();
con.setDoOutput(true);????//以后就可以使用conn.getOutputStream().write()??get用不到這個
con.setUseCaches(false);????//不使用緩存
/*?設置傳送的method=POST?*/
con.setRequestMethod("POST");
/*?setRequestProperty?*/
con.setRequestProperty("Connection",?"Keep-Alive");????//保持tcp連接
con.setRequestProperty("Charset",?"UTF-8");????????????//傳輸字符格式?UTF-8
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary="+boundary);
/*?設置DataOutputStream?*/
DataOutputStream?ds?=
new?DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens?+?boundary?+?end);
ds.writeBytes("Content-Disposition:?form-data;?"+
"name=\"file1\";filename=\""+
newName?+"\""+?end);
ds.writeBytes(end);
/*?取得文件的FileInputStream?*/
FileInputStream?fStream?=new?FileInputStream(uploadFile);
/*?設置每次寫入1024bytes?*/
int?bufferSize?=1024;
byte[]?buffer?=new?byte[bufferSize];
int?length?=-1;
/*?從文件讀取數據至緩沖區?*/
while((length?=?fStream.read(buffer))?!=-1)
{
/*?將資料寫入DataOutputStream中?*/
ds.write(buffer,?0,?length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens?+?boundary?+?twoHyphens?+?end);
/*?close?streams?*/
fStream.close();
ds.flush();
/*?取得Response內容?*/
InputStream?is?=?con.getInputStream();
int?ch;
StringBuffer?b?=new?StringBuffer();
while(?(?ch?=?is.read()?)?!=-1?)
{
b.append(?(char)ch?);
}
/*?將Response顯示于Dialog?*/
showDialog("上傳成功"+b.toString().trim());
/*?關閉DataOutputStream?*/
ds.close();
總結
以上是生活随笔為你收集整理的android系统提供了url通信,Android两种HTTP通信,HttpURLConnection和HttpClient的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php十六进制转为ascii,16进制转
- 下一篇: sitemesh 2.4