【HttpClient】发送post和get请求

 HttpClient发送get请求,post请求;HttpClient上传文件

package cn.gtmap.ias.datagovern.utils;

import org.apache.http.client.config.RequestConfig;
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.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;

public class HttpClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 设置连接超时时间,单位毫秒。
    private static final int CONNECT_TIMEOUT = 60000;

    // 请求获取数据的超时时间(即响应时间),单位毫秒。
    private static final int SOCKET_TIMEOUT = 60000;


    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException {

        String resultContent = "";

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 创建访问的地址
        URIBuilder uriBuilder;
        try {
            uriBuilder = new URIBuilder(url);
            if (params != null)
            {
                Set<Map.Entry<String, String>> entrySet = params.entrySet();
                for (Map.Entry<String, String> entry : entrySet)
                {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            // 封装请求头
            if (headers != null)
            {
                Set<Map.Entry<String, String>> entrySet2 = params.entrySet();
                for (Map.Entry<String, String> entry : entrySet2)
                {
                    // 设置到请求头到HttpRequestBase对象中
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                resultContent = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("返回结果" + resultContent);
            }

        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();

            return resultContent;
        }
    }

    public static String doPost(String url, Map<String, String> headers, String jsonString) throws IOException {

        String resultContent = "";

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;


        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout:设置连接超时时间,单位毫秒。
         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
         * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头
        /*
         * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
         * "keep-alive"); httpPost.setHeader("Accept", "application/json");
         * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
         * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
         * httpPost.setHeader("User-Agent",
         * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
         * );
         */
        // 封装请求头
        if (headers != null)
        {
            Set<Map.Entry<String, String>> entrySet2 = headers.entrySet();
            for (Map.Entry<String, String> entry : entrySet2)
            {
                // 设置到请求头到HttpRequestBase对象中
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        httpPost.setHeader("Content-Type", "application/json");
        // 封装请求参数
        httpPost.setEntity(new StringEntity(jsonString, ENCODING));

        // 执行请求
        response = httpclient.execute(httpPost);

        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 解析响应数据
            resultContent = EntityUtils.toString(response.getEntity(), "UTF-8");
//            System.out.println("返回结果:" + resultContent);
            logger.info("200返回结果:" + resultContent);
        }

        if (response != null) {
            response.close();
        }
        httpclient.close();

        return resultContent;

    }


}

HttpClient发送Post请求,用于上传图片:

 /**
     *
     * @param url
     * @param headers
     * @param filePath 文件路径
     * @param contentType 文件类型
     * @param params 接口其它参数
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> headers, String filePath, String contentType, Map<String, String> params) throws IOException {
        String resultContent = "";

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response;


        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout:设置连接超时时间,单位毫秒。
         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
         * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头
        /*
         * httpPost.setHeader("Cookie", ""); httpPost.setHeader("Connection",
         * "keep-alive"); httpPost.setHeader("Accept", "application/json");
         * httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
         * httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
         * httpPost.setHeader("User-Agent",
         * "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
         * );
         */
        // 封装请求头
        if (headers != null)
        {
            Set<Map.Entry<String, String>> entrySet2 = headers.entrySet();
            for (Map.Entry<String, String> entry : entrySet2)
            {
                // 设置到请求头到HttpRequestBase对象中
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        FileBody bin;
        if (contentType == null){
            bin = new FileBody(new File(filePath));
        }else {
            bin = new FileBody(new File(filePath), contentType);
        }

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("file", bin);

        if (params != null){
            for (String key : params.keySet()) {
                StringBody aa = new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8));
                multipartEntityBuilder.addPart(key, aa);
            }
        }


        HttpEntity reqEntity = multipartEntityBuilder.build();

        httpPost.setEntity(reqEntity);

        // 执行请求
        response = httpclient.execute(httpPost);

        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 解析响应数据
            resultContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("200返回结果:" + resultContent);
        }

        if (response != null) {
            response.close();
        }
        httpclient.close();

        return resultContent;

    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值