HttpClient

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient 提供的主要的功能

(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)

(2)支持自动转向

(3)支持 HTTPS 协议

(4)支持代理服务器等

带参数的GET请求

 

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请求

 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请求

 

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);
    }

}

 

  

 

posted @ 2018-03-25 21:37  Dear丶配角  阅读(205)  评论(0编辑  收藏  举报