Android-封裝post和get 網路請求

來源:互聯網
上載者:User

標籤: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 網路請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.