使用httpclient發送get或post請求


 

HttpClient 是 Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。當前官網最新版介紹頁是:http://hc.apache.org/httpcomponents-client-4.5.x/index.html

許多模擬http請求的框架都用httpclient,測試人員可通過它模擬請求http協議接口,做接口自動化測試。

1、包下載:
地址:http://mvnrepository.com/

        <!-- maven依賴 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

 

發送get請求

1、通過請求參數url和頭文件cookie作為參數(cookie可以為空)發送get請求,讀取返回內容

代碼如下:

public static String httpGet(String url,String cookie) throws Exception{  

        String result=""; //返回信息
        //創建一個httpGet請求
        HttpGet request=new HttpGet(url);
        //創建一個htt客戶端
        @SuppressWarnings("resource")
        HttpClient httpClient=new DefaultHttpClient();
        //添加cookie到頭文件
        request.addHeader("Cookie", cookie);
        //接受客戶端發回的響應
        HttpResponse httpResponse=httpClient.execute(request);
        //獲取返回狀態
        int statusCode=httpResponse.getStatusLine().getStatusCode();
        if(statusCode==HttpStatus.SC_OK){
            //得到客戶段響應的實體內容
            HttpEntity responseHttpEntity=httpResponse.getEntity();
            //得到輸入流
            InputStream in=responseHttpEntity.getContent();
            //得到輸入流的內容
            result=getData(in);
        }
        //Log.d(TAG, statusCode+"");
        return result;
    }

2、有時候,當我們想獲取返回頭文件信息,而不是返回內容時,只需要修改:

      //獲取返回狀態
        int statusCode=httpResponse.getStatusLine().getStatusCode();
        if(statusCode==HttpStatus.SC_OK){
            //取頭文件名(header值)信息
            strResult=httpResponse.getHeaders(header)[0].getValue().toString();
//            Header[] headers = httpResponse.getAllHeaders();//返回的HTTP頭信息
//            for (int i=0; i<headers.length; i++) {
//                System.out.println(headers[i]);
//            }
        }

 

發送post請求

1、請求地址、請求參數(map格式)、請求cookie作為參數發送Post請求

public static String httpPost(String url,Map<String,String> map,String cookie) {
        //返回body
        String body = "";  
        //1、創建一個htt客戶端
        @SuppressWarnings("resource")
        HttpClient httpClient=new DefaultHttpClient();
        //2、創建一個HttpPost請求
        HttpPost response=new HttpPost(url);
        
        //3、設置參數
        //建立一個NameValuePair數組,用於存儲欲傳送的參數
        List<NameValuePair> params = new ArrayList<NameValuePair>();  
        if(map!=null){  
            for (Entry<String, String> entry : map.entrySet()) {  
                //添加參數
                params.add( new BasicNameValuePair(entry.getKey(),entry.getValue()) );  
            }         
        }
        
        //4、設置參數到請求對象中  
        try {
            response.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }  //5、設置header信息  
        response.setHeader("Content-type", "application/x-www-form-urlencoded");  
        response.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
        //添加cookie到頭文件
        response.addHeader("Cookie", cookie);
        
        //6、設置編碼
        //response.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));      
        //7、執行post請求操作,並拿到結果(同步阻塞)  
        CloseableHttpResponse httpResponse;
        try {
            httpResponse = (CloseableHttpResponse) httpClient.execute(response);      
            //獲取結果實體  
            HttpEntity entity = httpResponse.getEntity();  
            if (entity != null) {  
                //按指定編碼轉換結果實體為String類型                
                body = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
        //釋放鏈接  
        httpResponse.close();          
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        return body;  
    }

 2、post請求獲取頭文件header信息

//7執行post請求
HttpResponse response = httpClient.execute(httpPost); //取頭信息 Header[] headers = response.getAllHeaders(); for(int i=0;i<headers.length;i++) { System.out.println(headers[i].getName() +"=="+ headers[i].getValue()); }

 

 

3、addHeader與setHeader區別

HttpClient在添加頭文件的時候,需要用到addHeader或setHeader

區別:

1、同名Header可以有多個 ,Header[] getHeaders(String name)。
2、運行時使用的是第一個, Header getFirstHeader(String name)。
3、addHeader,如果同名header已存在,則追加至原同名header后面
4、setHeader,如果同名header已存在,則覆蓋一個同名header

 

 

2、源代碼

鏈接:http://files.cnblogs.com/files/airsen/HttpClientUtil.rar

參考

1、httpclient中文翻譯:http://blog.csdn.net/column/details/httpclient.html

2、httpclient翻譯:http://blog.csdn.net/linghu_java/article/details/43306613

3、輕松把玩HttpClient之模擬post請求示例:http://blog.csdn.net/xiaoxian8023/article/details/49863967

 4、http://www.codeweblog.com/httpclient-%E6%93%8D%E4%BD%9C%E5%B7%A5%E5%85%B7%E7%B1%BB/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM