HttpClient使用

1.maven中添加其包

<!--  HttpClient 网络请求功能-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

2.代码

package com.zly.common.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 请求网络,模拟http请求
 * 
 * @Title HttpClienttUtils.java
 * @Description
 * @Create DateTime: 2018年8月19日 下午9:24:12
 * 
 * @author yuhf
 * 
 */
@Slf4j
public class HttpClientUtils {

    /**
     * 使用getHttp请求,访问数据,需要添加头文件
     * 
     * @param url
     *            路径
     * @param ip
     * @param userName
     *            接入方的账号
     * @param password
     *            密码
     * @param domainName
     *            域名
     * @return
     */
    public static ResponseBean getHttpAddHeader(String url, Map<String, String> mapHeader) {

        // 创建默认的httpClient实例
        CloseableHttpClient httpClient = getHttpClient();
        ResponseBean responseBean = new ResponseBean();

        try {
            // 用get方法发送http请求
            HttpGet get = new HttpGet(url);
            get = getAddHeader(mapHeader, get);

            log.info("HttpClientt执行get请求:...." + get.getURI());
            CloseableHttpResponse httpResponse = null;
            // 发送get请求
            httpResponse = httpClient.execute(get);

            // response实体
            HttpEntity entity = httpResponse.getEntity();
            // 添加返回数据
            if (null != entity) {
                responseBean.setCode(httpResponse.getStatusLine().getStatusCode());
                responseBean.setEntity(EntityUtils.toString(entity));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            closeHttpClient(httpClient);
        }

        return responseBean;
    }

    /**
     * get请求不要添加头文件
     * 
     * @param url
     * @return
     */
    public static ResponseBean getHttp(String url) {

        return getHttpAddHeader(url, null);
    }

    /**
     * 
     * @param url
     *            请求路径
     * @param map
     *            请求值<参数,参数值>
     * @param mapHeader
     *            头文件添加
     * @return ResponseBean
     * @throws Exception
     */
    public static ResponseBean postHttpAddHeader(String url, Map<String, String> map, Map<String, String> mapHeader) throws Exception {

        CloseableHttpClient httpClient = getHttpClient();
        ResponseBean responseBean = new ResponseBean();

        try {
            HttpPost post = new HttpPost(url); // 这里用上本机的某个工程做测试
            // 添加头文件
            post = postAddHeader(mapHeader, post);
            // map转换成list
            List<NameValuePair> list = mapToList(map);
            // url格式编码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
            post.setEntity(uefEntity);
            log.info("HttpClientt执行post请求:...." + post.getURI());
            // 执行请求
            CloseableHttpResponse httpResponse = httpClient.execute(post);
            HttpEntity entity = httpResponse.getEntity();

            // 添加返回数据
            if (null != entity) {
                responseBean.setCode(httpResponse.getStatusLine().getStatusCode());
                responseBean.setEntity(EntityUtils.toString(entity));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeHttpClient(httpClient);
        }

        return responseBean;
    }

    /**
     * post请求,不要添加头内容
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    private static ResponseBean postHttp(String url, Map<String, String> map) throws Exception {
        return postHttpAddHeader(url, map, null);
    }

    /**
     * post请求,接入方权限请求
     * 
     * @param url
     *            请求路径
     * @param userName
     *            账户
     * @param password
     *            密码
     * @param ip
     * @return ResponseBean
     * @throws Exception
     */
    public static ResponseBean postHttpHeaderByCaller(String url, String userName, String password, String ip, String domainName) throws Exception {

        Map<String, String> map = new HashMap<String, String>();
        map.put("userName", userName);
        map.put("password", password);
        map.put("ip", ip);
        map.put("domainName", domainName);
        ResponseBean postHttpHeader = postHttp(url, map);
        return postHttpHeader;
    }

    /**
     * map转list
     * 
     * @param map
     * @return
     * @throws Exception
     */
    private static List<NameValuePair> mapToList(Map<String, String> map) throws Exception {

        // 创建参数列表
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if (null != map) {
            for (Map.Entry<String, String> entry : map.entrySet()) {

                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        return list;
    }

    /**
     * post添加头文件
     * 
     * @param map
     * @param post
     * @return
     * @throws Exception
     */
    private static HttpPost postAddHeader(Map<String, String> map, HttpPost post) throws Exception {

        if (null != map) {

            for (Map.Entry<String, String> entry : map.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return post;
    }

    /**
     * get添加头文件
     * 
     * @param map
     * @param get
     * @return
     * @throws Exception
     */
    private static HttpGet getAddHeader(Map<String, String> map, HttpGet get) throws Exception {
        if (null != map) {

            for (Map.Entry<String, String> entry : map.entrySet()) {
                get.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return get;
    }

    /**
     * get方式请求
     * 
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

    /**
     * 关闭httpclient链接
     * 
     * @param client
     * @throws IOException
     */
    private static void closeHttpClient(CloseableHttpClient client) {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 返回的bean
     * 
     * @author yuhf
     *
     */
    public static class ResponseBean {

        /** 请求网络返回正确 */
        public final static String CODE_SUCCESS = "0";

        // 响应状态码
        private int code;
        // 响应状内容
        private String entity;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getEntity() {
            return entity;
        }

        public void setEntity(String entity) {
            this.entity = entity;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值