我是靠谱客的博主 野性盼望,最近开发中收集的这篇文章主要介绍httpClient4.3x 使用4.3版本简介2、工具代码使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

4.3版本简介

1、创建HTTP客户端

CloseableHttpClient client = HttpClientBuilder.create().build(); 

2、发送基本的GET请求

instance.execute(new HttpGet(“http://www.baidu.com”));  

3、获取HTTP响应的状态码

    String url = “http://www.baidu.com;  
    CloseableHttpResponse response = instance.execute(new HttpGet(url));  
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));  

4、获取响应的媒体类型

String url = “http://www.baidu.com;  
    CloseableHttpResponse response = instance.execute(new HttpGet(url));  
    String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();  
    assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType())); 

5、获取响应的BODY部分

    String url = “http://www.baidu.com;  
     CloseableHttpResponse response = instance.execute(new HttpGet(url));  
    String bodyAsString = EntityUtils.toString(response.getEntity());  
    assertThat(bodyAsString, notNullValue()); 

6、配置请求的超时设置

public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws       ClientProtocolException, IOException{  
    RequestConfig requestConfig = RequestConfig.custom()  
     .setConnectionRequestTimeout(50).setConnectTimeout(50)  
     .setSocketTimeout(50).build();  
    HttpGet request = new HttpGet(SAMPLE_URL);  
    request.setConfig(requestConfig);  
    instance.execute(request);  
}  

7、发送POST请求

instance.execute(new HttpPost(SAMPLE_URL));  

8、为HTTP请求配置重定向

CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();  
CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));  
assertThat(reponse.getStatusLine().getStatusCode(), equalTo(301)); 

9、配置请求的HEADER部分

HttpGet request = new HttpGet(SAMPLE_URL);  
request.addHeader(HttpHeaders.ACCEPT, “application/xml”);  
response = instance.execute(request); 

10、获取响应的HEADER部分

CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));  
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);  
assertThat(headers, not(emptyArray()));  

11、关闭或释放资源

response = instance.execute(new HttpGet(SAMPLE_URL));  
    try{  
           HttpEntity entity = response.getEntity();  
          if(entity!=null){  
          InputStream instream = entity.getContent();  
          instream.close();  
       } finally{  
          response.close();  
 }  

2、工具代码使用

package com.util.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * 网络请求V3.0
 * @author yanbumo
 */
public class Net {

    HttpClient client;
    HttpUriRequest request;
    HttpResponse response;

    private MultipartEntityBuilder multipartEntityBuilder;
    private Map<String, Object> params;

    public Net() {
        client = HttpClientBuilder.create().build();
    }

    /**
     * 设置请求超时
     * @param conTime
     * @param socketTime
     * @return
     */
    public Net setTimeOut(int conTime,int socketTime){
        RequestConfig config = RequestConfig.custom().setConnectTimeout(conTime).setSocketTimeout(socketTime).build();
        setRequestConfig(config);
        return this;
    }

    public Net setRequestConfig(RequestConfig config){
        if(request.getClass().equals(HttpGet.class)){
            ((HttpGet)request).setConfig(config);
        }else if(request.getClass().equals(HttpPost.class)){
            ((HttpPost)request).setConfig(config);
        }
        return this;
    }

    /**
     * GET请求
     * @param url
     * @return
     */
    public Net get(String url){
        request = new HttpGet(url);
        params = new HashMap<>();
        return this;
    }

    /**
     * POST 请求
     * @param url
     * @return
     */
    public Net post(String url){
        request = new HttpPost(url);
        multipartEntityBuilder = MultipartEntityBuilder.create();
        return this;
    }

    /**
     * 添加请求头
     * @param headers
     * @return
     */
    public Net addHead(Header...headers){
        for (Header header : headers) {
            request.addHeader(header);
        }
        return this;
    }

    /**
     * 添加请求头
     * @param name
     * @param value
     * @return
     */
    public Net addHead(String name,Object value){
        request.addHeader(name, value.toString());
        return this;
    }

    /**
     * 添加Cookie
     * @param cookie
     * @return
     */
    public Net addCookie(String cookie){
        return addHead("Cookie", cookie);
    }

    /**
     * 添加参数
     * @param name
     * @param value
     * @return
     */
    public Net addParams(String name,Object value){
        if(request.getClass().equals(HttpGet.class)){
            addParamsGet(name, value);
        }else if(request.getClass().equals(HttpPost.class)){
            addParamsPost(name, value);
        }
        return this;
    }

    private void addParamsGet(String name,Object value){
        params.put(name, value);
    }

    private void addParamsPost(String name,Object object){
        if(object.getClass().equals(File.class)){
            FileBody body = new FileBody((File)object);
            multipartEntityBuilder.addPart(name, body);
        }else{
            multipartEntityBuilder.addTextBody(name, object.toString());
        }
    }

    /**
     * 执行请求
     * @return
     */
    public Net doRequest(){
        try{
            if(request.getClass().equals(HttpGet.class)){
                doGet();
            }else if(request.getClass().equals(HttpPost.class)){
                doPost();
            }
            response = client.execute(request);
        }catch(Exception e){
            e.printStackTrace();
        }
        return this;
    }

    private void doGet() throws URISyntaxException{
        if(params.isEmpty()){
            return;
        }
        String url = "";
        Set<String> keys = params.keySet();
        for (String key : keys) {
            url += "&" + key + params.get(key);
        }
        url = url.replaceFirst("&", "?");
        HttpGet get = (HttpGet)request;
        get.setURI(new URI(get.getURI() + url));
        this.request = get;
    }

    private void doPost(){
        HttpPost post = (HttpPost)request;
        post.setEntity(multipartEntityBuilder.build());
        this.request = post;
    }

    /**
     * 得到返回体
     * @return
     */
    public HttpResponse getResult(){
        return this.response;
    }
    /**
     * 得到Cookie
     * @return
     */
    public Header[] getCookie(){
        return response.getHeaders("Set-Cookie");
    }

    /**
     * 得到返回字符串
     * @return
     */
    public String getStr(){
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            try{
                return EntityUtils.toString(response.getEntity());
            }catch(Exception e){
                return null;
            }
        }
        return response.getStatusLine().getStatusCode() + "";
    }
    /**
     * 下载文件 (单个文件)
     * @param filePath
     * @return
     */
    public File getFile(String filePath){
        try{
            File file = new File(filePath);
            if(! file.exists()){
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            InputStream inputStream = response.getEntity().getContent();
            OutputStream outputStream = new FileOutputStream(file);
             int index = 0;
             byte[] btys = new byte[4096];
             while(( index = inputStream.read( btys)) != -1){
                   outputStream.write( btys, 0, index);
            }
             inputStream.close();
             outputStream.flush();
             outputStream.close();
             return file;


        }catch(Exception e){
            return null;
        }
    }

}

测试用例

Net net = new Net();
Header[] cookies = net.post("http://host:8080/user/login")
        .addParams("username", "username").addParams("pswd", "pswd")
        .doRequest().getCookie();
String rs = net.get("http://host:8080/sign/mysignpage=1&step=1000&type=1")
    .addHead(cookies).setTimeOut(10, 1000)
    .doRequest().getStr();

最后

以上就是野性盼望为你收集整理的httpClient4.3x 使用4.3版本简介2、工具代码使用的全部内容,希望文章能够帮你解决httpClient4.3x 使用4.3版本简介2、工具代码使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(28)

评论列表共有 0 条评论

立即
投稿
返回
顶部