HttpClient

HttpClient 是 Apache Jakarta Common 下的子項目,能夠用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。編程

HttpClient 提供的主要的功能服務器

(1)實現了全部 HTTP 的方法(GET,POST,PUT,DELETE 等)工具

(2)支持自動轉向post

(3)支持 HTTPS 協議ui

(4)支持代理服務器等this

帶參數的GET請求url

 

public static void main(String[] args) throws Exception {

    // 建立Httpclient對象
    CloseableHttpClient httpclient = HttpClients.createDefault();

    // http://www.baidu.com/rest/content?categoryId=32&page=1&rows=20
    // 定義請求的參數
    URI uri = new URIBuilder("http://www.baidu.com/rest/content").setParameter("categoryId", "32").setParameter("page", "1").setParameter("rows", "20").build();

    System.out.println(uri);

    // 建立http GET請求
    HttpGet httpGet = new HttpGet(uri);

    CloseableHttpResponse response = null;
    try {
        // 執行請求
        response = httpclient.execute(httpGet);
        // 判斷返回狀態是否爲200
        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(content);
        }
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }

}

 

 

  

POST請求spa

 1 public static void main(String[] args) throws Exception {
 2 
 3     // 建立Httpclient對象
 4     CloseableHttpClient httpclient = HttpClients.createDefault();
 5 
 6     // 建立http POST請求
 7     HttpPost httpPost = new HttpPost("http://www.oschina.net/");
 8 
 9     // 在請求中設置請求頭,設置請求頭,跳過開源中國的訪問限制
10     httpPost.setHeader("User-Agent", "");
11 
12     CloseableHttpResponse response = null;
13     try {
14         // 執行請求
15         response = httpclient.execute(httpPost);
16         // 判斷返回狀態是否爲200
17         if (response.getStatusLine().getStatusCode() == 200) {
18             String content = EntityUtils.toString(response.getEntity(), "UTF-8");
19             System.out.println(content);
20         }
21     } finally {
22         if (response != null) {
23             response.close();
24         }
25         httpclient.close();
26     }
27 
28 }

 

  

帶參數POST請求.net

 

public static void main(String[] args) throws Exception {

    // 建立Httpclient對象
    CloseableHttpClient httpclient = HttpClients.createDefault();

    // 建立http POST請求
    HttpPost httpPost = new HttpPost("http://manager.jd.com/rest/item/interface");

    // 設置2個post參數,一個是scope、一個是q
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
    // parameters.add(new BasicNameValuePair("scope", "project"));
    parameters.add(new BasicNameValuePair("price", "123000"));
    parameters.add(new BasicNameValuePair("title", "httpclient123"));
    parameters.add(new BasicNameValuePair("cid", "380"));
    parameters.add(new BasicNameValuePair("status", "1"));
    parameters.add(new BasicNameValuePair("num", "123"));
    // 構造一個form表單式的實體
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
    // 將請求實體設置到httpPost對象中
    httpPost.setEntity(formEntity);

    CloseableHttpResponse response = null;
    try {
        // 執行請求
        response = httpclient.execute(httpPost);
        // 判斷返回狀態是否爲200
        if (response.getStatusLine().getStatusCode() == 201) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(content);
        }
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}

 

 

  

自動跳轉

httpclient4.0版本中,使用get請求時,遇到302會自動跳轉,若是須要獲得302中location的信息,代理

能夠用post方法去請求或者把get自動處理重定向禁掉。 

要禁用get方法自動處理重定向,須要設一下參數: 

  1. HttpClient httpclient = new DefaultHttpClient();    
  2. HttpParams params = httpclient.getParams();    
  3. params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);    

HttpClient4.3中默認容許自動重定向,致使程序中不能跟蹤跳轉狀況,其實只須要在RequestConfig中setRedirectsEnabled(false)便可(默認是true)

private RequestConfig createConfig(int timeout, boolean redirectsEnabled)
{
    retun RequestConfig.custom()
        .setSocketTimeout(timeout)
        .setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setRedirectsEnabled(redirectsEnabled)
        .build();
}
public void test(String url)
{
  CloseableHttpClient client = HttpClients.createDefault();   
    try  
    {    
        HttpGet httpGet = new HttpGet(url);    
        httpGet.setConfig(createConfig(5000, false));    
        CloseableHttpResponse response = client.execute(httpGet);    
        try    
        {      
            Header h = response.getFirstHeader("Location");      
            if(h!=null)      
            {         
                System.out.println("重定向地址:"+h.getValue());      
            }    
        }    
        finally    
        {      
            response.close();    
        }  
    }  
    finally  
    {  
      client.close();  
    }
}

 

  

使用代理服務

 

// 依次是目標請求地址,端口號,協議類型  
HttpHost target = new HttpHost("10.10.100.102:8080/mytest", 8080,
        "http");
// 依次是代理地址,代理端口號,協議類型  
HttpHost proxy = new HttpHost("yourproxy", 8080, "http");
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

// 請求地址  
HttpPost httpPost = new HttpPost("http://10.10.100.102:8080/mytest");
httpPost.setConfig(config);
// 建立參數隊列  
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
// 參數名爲pid,值是2  
formparams.add(new BasicNameValuePair("pid", "2"));
UrlEncodedFormEntity entity;
try {
    entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    httpPost.setEntity(entity);
    CloseableHttpResponse response = httpClient.execute(
            target, httpPost);
    // getEntity()  
    HttpEntity httpEntity = response.getEntity();
    if (httpEntity != null) {
        // 打印響應內容  
        System.out.println("response:"
                + EntityUtils.toString(httpEntity, "UTF-8"));
    }
    // 釋放資源  
    httpClient.close();
} catch (Exception e) {
    e.printStackTrace();
}

 

 

  

使用HttpClient調用接口

  編寫返回對象

  

public class HttpResult {
    // 響應的狀態碼
    private int code;

    // 響應的響應體
    private String body;
get/set…
}

 

  

封裝HttpClient

/**
     * 帶參數的get請求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map) throws Exception {
        // 1.建立URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 2.設置請求參數
        if (map != null) {
            // 遍歷請求參數
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封裝請求參數
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 3.建立請求對象httpGet
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 4.使用httpClient發起請求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 5.解析返回結果,封裝返回對象httpResult
        // 獲取狀態碼
        int code = response.getStatusLine().getStatusCode();

        // 獲取響應體
        // 使用EntityUtils.toString方法必須保證entity不爲空
        String body;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        } else {
            body = null;
        }

        return new HttpResult(code, body);
    }

 

  

/**
     * 不帶參數的get
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url) throws Exception {
        return this.doGet(url, null);
    }

 

  

/**
     * 帶參數的post請求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 1. 聲明httppost
        HttpPost httpPost = new HttpPost(url);

        // 2.封裝請求參數,請求數據是表單
        if (map != null) {
            // 聲明封裝表單數據的容器
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封裝請求參數到容器中
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 建立表單的Entity類
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");

            // 3. 把封裝好的表單實體對象設置到HttpPost中
            httpPost.setEntity(entity);
        }

        // 4. 使用Httpclient發起請求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        // 5. 解析返回數據,封裝HttpResult
        // 狀態碼
        int code = response.getStatusLine().getStatusCode();

        // 響應體內容
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        return new HttpResult(code, body);
    }

 

  

/**
     * 不帶參數的post請求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        return this.doPost(url, null);
    }

 

  

/**
     * 帶參數的put請求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // HttpPost httpPost = new HttpPost(url);
        // 1. 聲明httpPut
        HttpPut httpPut = new HttpPut(url);

        // 2.封裝請求參數,請求數據是表單
        if (map != null) {
            // 聲明封裝表單數據的容器
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封裝請求參數到容器中
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 建立表單的Entity類
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");

            // 3. 把封裝好的表單實體對象設置到HttpPost中
            httpPut.setEntity(entity);
        }

        // 4. 使用Httpclient發起請求
        CloseableHttpResponse response = this.httpClient.execute(httpPut);

        // 5. 解析返回數據,封裝HttpResult
        // 狀態碼
        int code = response.getStatusLine().getStatusCode();

        // 響應體內容
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        return new HttpResult(code, body);
    }

 

  

/**
     * 帶參數的delete
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
        // 1.建立URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 2.設置請求參數
        if (map != null) {
            // 遍歷請求參數
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封裝請求參數
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 3.建立請求對象httpDelete
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 4.使用httpClient發起請求
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);

        // 5.解析返回結果,封裝返回對象httpResult
        // 獲取狀態碼
        int code = response.getStatusLine().getStatusCode();

        // 獲取響應體
        // 使用EntityUtils.toString方法必須保證entity不爲空
        String body;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        } else {
            body = null;
        }

        return new HttpResult(code, body);
    }

}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息