学习整理HttpClient4.5成http访问服务类

在项目中经常有访问http的需要,HttpClient是一个Apache下一个传统又实用的http工具包,看了介绍,每个版本变化挺大,网上资料也好多是3.X版本,如下是我整理的对4.5.2版本的封装,提供了get和post方法的简便使用,这里使用的方法比较传统,下篇再介绍使用Fluent API封装get和post方法,代码将是简洁流畅。

HttpClient官网:

https://hc.apache.org/index.html

HttpClient分为5大组件,我用了其中两个。

mavne依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.2</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.1</version>
</dependency>

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>

get和post方法的封装:

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @author wzx
 * @time 2017/1/19
 */
public class HttpService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpService.class);

    public String doGet(String url) {
        return doGet(url, null);
    }

    public String doGet(String url, Map<String, String> parameters) {
        return doGet(url, null, null, null, parameters);
    }

    public String doGet(String url, String hostName, Integer port, String schemeName, Map<String, String> parameters) {
        CloseableHttpClient client = buildClient(hostName, port, schemeName);
        return executeGet(client, url, parameters);
    }

    public String doPost(String url) {
        return doPost(url, null);
    }

    public String doPost(String url, List<NameValuePair> nameValuePairs) {
        return doPost(url, null, null, null, nameValuePairs, null);
    }

    public void doPost(String url, List<NameValuePair> nameValuePairs, List<File> files) {
        doPost(url, null, null, null, nameValuePairs, files);
    }

    public String doPost(String url, String hostName, Integer port, String schemeName, List<NameValuePair> nameValuePairs, List<File> files) {
        CloseableHttpClient client = buildClient(hostName, port, schemeName);
        return executePost(client, url, nameValuePairs, files);
    }

    /**
     * 构建HttpClient
     * @param hostName 代理主机
     * @param port 代理主机端口
     * @param schemeName 默认是http
     * @return 不使用代理返回默认的httpClient
     */
    private CloseableHttpClient buildClient(String hostName, Integer port, String schemeName) {
        CloseableHttpClient httpClient;
        if(StringUtils.isEmpty(hostName) || port == null) {
            //不使用代理
            httpClient = HttpClients.createDefault();
        } else {
            //设置代理
            if (StringUtils.isEmpty(schemeName)) {
                schemeName = HttpHost.DEFAULT_SCHEME_NAME;
            }
            HttpHost httpHost = new HttpHost(hostName, port, schemeName);
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(httpHost);
            httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build();
        }
        return httpClient;
    }

    /**
     * 执行GET请求
     * @param client
     * @param url
     * @param paramMap
     * @return
     */
    private String executeGet(CloseableHttpClient client, String url, Map<String, String> paramMap) {
        Assert.notNull(url, "url is null");
        Assert.notNull(client, "closeableHttpClient is null");

        if(MapUtils.isNotEmpty(paramMap)) {
            List<NameValuePair> paramList = Lists.newArrayListWithCapacity(paramMap.size());
            for (String key : paramMap.keySet()) {
                paramList.add(new BasicNameValuePair(key, paramMap.get(key)));
            }
            //拼接参数
            url += "?" + URLEncodedUtils.format(paramList, Consts.UTF_8);
        }

        CloseableHttpResponse response = null;
        try {
            HttpGet get = new HttpGet(url);
            response = client.execute(get);
            return processResponse(response);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e.toString());
        } finally {
            close(client, response);
        }
        return null;
    }

    /**
     * 执行POST请求
     * @param httpClient
     * @param url
     * @param nameValuePairs
     * @return
     */
    private String executePost(CloseableHttpClient httpClient, String url, List<NameValuePair> nameValuePairs, List<File> files) {
        Assert.notNull(url, "url is null");
        Assert.notNull(httpClient, "closeableHttpClient is null");
        CloseableHttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            HttpEntity entity = buildPostParam(nameValuePairs, files);
            if(entity != null) {
                post.setEntity(entity);
            }
            response = httpClient.execute(post);
            return processResponse(response);
        } catch(Exception e) {
            LOGGER.error(e.getMessage(), e.toString());
        } finally {
            close(httpClient, response);
        }
        return null;
    }

    /**
     * 构建POST方法请求参数
     * @return
     */
    private HttpEntity buildPostParam(List<NameValuePair> nameValuePairs, List<File> files) {
        if(CollectionUtils.isEmpty(nameValuePairs) && CollectionUtils.isEmpty(files)) {
            return null;
        }
        if(CollectionUtils.isNotEmpty(files)) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (File file : files) {
                builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
            }
            for (NameValuePair nameValuePair : nameValuePairs) {
                //设置ContentType为UTF-8,默认为text/plain; charset=ISO-8859-1,传递中文参数会乱码
                builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), ContentType.create("text/plain", Consts.UTF_8));
            }
            return builder.build();
        } else {
            try {
                return new UrlEncodedFormEntity(nameValuePairs);
            } catch (UnsupportedEncodingException e) {
                LOGGER.error(e.getMessage(), e.toString());
            }
        }
        return null;
    }

    private String processResponse(CloseableHttpResponse response) {
        try {
            if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, Consts.UTF_8);
                }
            }
        } catch(Exception e) {
            LOGGER.error(e.getMessage(), e.toString());
        } finally {
            close(null, response);
        }
        return null;
    }

    private void close(CloseableHttpClient httpClient, CloseableHttpResponse response) {
        try {
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e.toString());
        }
    }

}

单元测试:

private String url = "https://hc.apache.org/httpcomponents-client-4.5.x/examples.html";

@Test
public void testGet() {
    String result = httpService.doGet(url);
    LOGGER.info("返回结果:{}", result);
}

@Test
public void testGetParameter() {
    HashMap<String, String> map = Maps.newHashMap();
    map.put("name", "wang");
    map.put("value", "hello");
    String result = httpService.doGet(url, null);
    LOGGER.info("返回结果:{}", result);
}

@Test
public void testGetProxy() {
    String result = httpService.doGet(url, "119.28.99.246", 8998, null, null);
    LOGGER.info("返回结果:{}", result);
}

@Test
public void testPost() {
    String result = httpService.doPost(url, null);
    LOGGER.info("返回结果:{}", result);
}

@Test
public void testPostProxy() {
    String result = httpService.doPost(url, "119.28.99.246", 8998, null, null, null);
    LOGGER.info("返回结果:{}", result);
}

@Test
public void testPostParam() throws IOException, URISyntaxException {
    List<NameValuePair> nameValuePairs = Lists.newArrayList();
    nameValuePairs.add(new BasicNameValuePair("name", "王志雄"));
    List<File> fileList = Lists.newArrayList();
    fileList.add(new File("D:\\response.html"));
    String result = httpService.doPost(url, "localhost", 8888, HttpHost.DEFAULT_SCHEME_NAME, nameValuePairs, fileList);
    LOGGER.info("返回结果:{}", result);
}

有问题可以留言探讨。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值