標籤:httpclient httpurlconnection httppost httpget httpeneity
1.背景 在開發android 的時候,網路請求時必不可少的,在此,封裝成一個類,方便調用;
2.注意 在這裡實現了 HttpUrlConnection (不是HttpsUrlConnection)的get請求和 HttpClient 的 Get和 Post請求! 這裡封裝的僅僅是資料的操作,不包括 圖片的請求和上傳!
3.HttpUrlConnection 實現 這個請求成功後,需要使用 IO流來讀取!
public static String getData() throws Exception{ try {//HttpPath.GetGamesPath() : 網路請求路徑URL url=new URL(HttpPath.GetGamesPath());HttpURLConnection conn=(HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");if(conn.getResponseCode()==200){ InputStream ips=conn.getInputStream(); byte[] data=read(ips); String str=new String(data); System.out.println(str); return str;}else{ return "網路錯誤 :conn.getResponseCode() ="+conn.getResponseCode();}} catch (MalformedURLException e) {// TODO Auto-generated catch blockreturn "HttpService.getGamesData()發生異常! "+e.getMessage();}} /* * 讀取流中的資料 * */public static byte[] read(InputStream inStream) throws Exception {ByteArrayOutputStream outStream=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=0;while((len=inStream.read(buffer))!=-1){outStream.write(buffer,0,len);}inStream.close();return outStream.toByteArray();}
4.Httpclient , Httppost , EneityUtils 實現 post 請求操作 這裡注意的是傳參數的時候需要的是 List<BasicNameValuePair> , 參數格式化 需要的是 UrlEncodeFormEntity 方法!
/** * httpclient post提交資料 * @param parameters * @return * @throws ClientProtocolException * @throws IOException */public static String toPostdata(List<BasicNameValuePair> parameters) throws ClientProtocolException, IOException{String str="擷取失敗";//初始化HttpClient client=new DefaultHttpClient();//HttpPath.GetGamesPath() : 網路請求路徑HttpPost httpPost=new HttpPost(HttpPath.GetGamesPath());//設定參數UrlEncodedFormEntity params=new UrlEncodedFormEntity(parameters,"UTF-8"); httpPost.setEntity(params); //執行請求 HttpResponse response= client.execute(httpPost); //取得傳回值if(response.getStatusLine().getStatusCode()==200){//請求成功HttpEntity entity=response.getEntity();str=EntityUtils.toString(entity, "UTF-8");}return str;}
5.Httpclient , Httpget , EneityUtils 實現 get請求操作
/** * httpclient get 獲得資料 * @return */public static String toGetData(){String str="擷取資料失敗";HttpClient client=new DefaultHttpClient();////HttpPath.GetGamesPath() : 網路請求路徑HttpGet get=new HttpGet(HttpPath.GetGamesPath()); try { HttpResponse httpResponse=client.execute(get); if(httpResponse.getStatusLine().getStatusCode()==200){ str=EntityUtils.toString(httpResponse.getEntity(),"UTF-8"); } return str; } catch (ClientProtocolException e) {// TODO Auto-generated catch blockreturn "toGetData 異常:"+e.getMessage();} catch (IOException e) {// TODO Auto-generated catch blockreturn "toGetData 異常:"+e.getMessage();}}
6.對比 相比之下 HttpClient 比 HttpUrlConnection 更方便些,但是 還是看習慣而言!
7.工具類下載 http://download.csdn.net/detail/lablenet/9005725
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android-封裝post和get 網路請求