使用HttpClient对象发送post和get HTTP请求的方法和注意点

package com.fish.common.http;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpResponseException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

public class HttpClientUtils {


    /**
     * @Description post请求发送
     * @Param [url, requestDataJson]
     * @return java.lang.String
     **/
    public static String doPost(String url, String requestDataJson, Header[] heades) throws Exception {
        CloseableHttpClient httpClient=null;
        CloseableHttpResponse httpResponse=null;

        //创建httpClient连接对象
        httpClient = createSSLClientDefault();//HttpClients.custom().build();
        //创建post请求连接对象
        HttpPost httpPost = new HttpPost(url);
        //创建连接请求参数对象,并设置连接参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)		//连接服务器主机超时时间
                .setConnectionRequestTimeout(60000)  //连接请求超时时间
                .setSocketTimeout(6000)				//设置读取响应数据超时时间
                .build();

        //为httpPost请求设置参数
        httpPost.setConfig(requestConfig);
        ContentType contentType = ContentType.create("application/json","UTF-8");
        //将上传参数存放到entity属性中
        httpPost.setEntity(new StringEntity(requestDataJson,contentType));
        //添加头信息
        httpPost.setHeaders(heades);

        String result="";
        //发送请求
        try {
            httpResponse = httpClient.execute(httpPost);
            //获取返回内容
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
        } catch (IOException e) {
            throw new Exception(e);
        } finally {
            if (httpPost != null) {
                httpPost.abort();
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    /**
     * @Description get请求发送
     * @Param [url, requestDataJson]
     * @return java.lang.String
     **/
    public static String doGet(String url, Header[] heades) throws Exception {
        CloseableHttpClient httpClient=null;
        CloseableHttpResponse httpResponse=null;

        //创建httpClient连接对象
        httpClient = createSSLClientDefault();//HttpClients.custom().build();
        //创建get请求连接对象
        HttpGet httpGet = new HttpGet(url);
        //创建连接请求参数对象,并设置连接参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000)		//连接服务器主机超时时间
                .setConnectionRequestTimeout(60000)  //连接请求超时时间
                .setSocketTimeout(6000)				//设置读取响应数据超时时间
                .build();

        //为httpGet请求设置参数
        httpGet.setConfig(requestConfig);
        //添加头信息
        httpGet.setHeaders(heades);

        String result="";
        //发送请求
        try {
            httpResponse = httpClient.execute(httpGet);
            //获取返回内容
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
        } catch (IOException e) {
            throw new Exception(e);
        } finally {
            if (httpGet != null) {
                httpGet.abort();
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 创建一个SSL信任所有证书的httpClient对象
     *
     * @return
     */
    public static CloseableHttpClient createSSLClientDefault(){
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
                    return true;
                }

            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }
}

使用get请求中经常会有一些拼接参数出现中文字符等等非法字符如果不进行转码会出现报错

Illegal character in query at index 124: https://api.topthink.com/sms/send?appCode=xxxxxxxxx&signId=xxx&templateId=xx&phone=XXXXXXXX&params={\"code\":\"xxxxx\"} 

我们只需要把含有非法字符的params=后的数据通过URLEncoder进行转编码即可

解决方案如下:

param1 = URLEncoder.encode(params, "UTF-8");

把参数进行转编码后再放入到url内即可

https://api.topthink.com/sms/send?appCode=xxxxxxxxxxxxx&signId=xxx&templateId=xxx&phone=xxxxxx&params=%7B%22code%22%3A%221481%22%7D

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值