【安卓學習筆記】HTTP請求——HttpClient方式

主要知識點:

  • 不能緩存服務器響應,一般用于抓包
  • 相較于HttpUrlConnection來說,不需要關心各種輸入輸出流的轉換
  • 步驟:獲取HttpUrlConnection,獲取HttpGet、HttpPost、execute獲取響應(判斷狀態(tài)碼)、對響應結果(Entity)進行轉換
  • HttpPost/HttpGet.setHeader設置請求頭,從response獲取cookie等響應頭信息

源碼:

public class HttpClientRequest {

        public String getData(String path) throws Exception{
                                
                    HttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(path);
                    
                    HttpResponse response = client.execute(httpGet);
                    
                    if(response.getStatusLine().getStatusCode()==200){
                        HttpEntity entity = response.getEntity();
                        String data = EntityUtils.toString(entity,"utf-8");
                        return data;
                    }                   
            
            return null;
        }
        
        public String postData(String path,List<NameValuePair> parameters) throws Exception{
            
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(path);
                        
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
            httpPost.setEntity(entity);
            
            HttpResponse response = client.execute(httpPost);
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity responseEntity = response.getEntity();
                String data = EntityUtils.toString(responseEntity,"utf-8");
                return data;
            }
            return null;
        }
        
        
}

調用:

new Thread(){
            public void run() {             
                
                try {
                    HttpClientRequest hcr = new HttpClientRequest();
                    
                    /******************GET方式請求*********************/
                    //String str =hcr.getData("http://192.168.1.183/test.php?name=123");
                    
                    /******************POST方式請求*********************/
                    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                    parameters.add(new BasicNameValuePair("name", "xiaoming"));
                    
                    String str = hcr.postData("http://192.168.1.183/test.php",parameters);
                    
                    System.out.println(str);
                    
                } catch (Exception e) {                 
                    e.printStackTrace();
                }
                
            };
}.start();
參考自:http://www.runoob.com/w3cnote/android-tutorial-httpclient.html
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容