后端发送HTTP请求_一个http请求发送到后端-程序员宅基地

技术标签: java  实习  http  okhttp  

后端发送HTTP请求

1 原始方式

背景:
get:获取微信的accessToken
post:设置微信公众号的自定义菜单

1.1 get方式

//get方式发起请求
public String get(String url){
    
    try{
    
        URL urlObj = new URL(url);
        //开连接
        URLConnection connection = urlObj.openConnection();
        InputStream is = connection.getInputStream();
        byte[] b = new byte[1024];
        int len;
        StringBuilder stb = new StringBuilder();
        while((len=is.read(b)) != -1){
    
            stb.append(new String(b, 0, len));
        }
        return stb.toString();
    } catch (Exception e){
    
        e.printStackTrace();
    }
    return null;
}

1.2 post方式

//post方式发起请求,data是请求体
public static String post(String url, String data){
    
    try{
    
        URL urlObj = new URL(url);
        URLConnection connection = urlObj.openConnection();
        //要发送数据出去,必须要设置为可发送数据状态
        connection.setDoOutput(true);
        //获取输出流
        OutputStream os = connection.getOutputStream();
        //写出数据
        os.write(data.getBytes());
        os.close();
        //获取输入流
        InputStream is = connection.getInputStream();
        byte[] b = new byte[1024];
        int len;
        StringBuilder stb = new StringBuilder();
        while((len = is.read(b)) != -1){
    
            stb.append(new String(b, 0, len));
        }
        return stb.toString();
    } catch (Exception e){
    
        e.printStackTrace();
    }
    return null;
}

2 使用OKHttp

导入依赖:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.8.0</version>
</dependency>

2.1 基本方式

①通过get方式
public void OkHttpGet(String url) {
    
    OkHttpClient okHttpClient = new OkHttpClient();
    //不配url方法会报错,肯定要有访问地址的嘛
    //.Builder是Request内部类 .url()返回Builder .build()返回Request对象
    Request request = new Request.Builder()
            //.addHeader("a", "b")//.addHeader添加键值对header信息
            //.get()//可加可不加
            .url(url)
            .build();
    Call call = okHttpClient.newCall(request);
    try {
    
        Response response = call.execute();
        System.out.println(response.body().string());
        //http状态码
        System.out.println(response.code());
        //response的头信息
        System.out.println(response.headers().toString());
        //请求响应时间,收到时间减去发送的时间,单位毫秒
        System.out.println(response.receivedResponseAtMillis()-response.sentRequestAtMillis());
    } catch (IOException e) {
    
        e.printStackTrace();
    }
}
②通过post方式
public void OkHttpPost(String url){
    
     //ssl认证重写
    OkHttpClient okHttpClient=new OkHttpClient.Builder().hostnameVerifier(
            new HostnameVerifier() {
    
                @Override
                public boolean verify(String s, SSLSession sslSession) {
    
                    return true;
                }
            }
    ).build();
    RequestBody requestBody=new FormBody.Builder()
            .add("oldPassword","111111")
            .add("newPassword","111111")
            .build();

    Request request=new Request.Builder()
            .url(url)
            .post(requestBody)
            .addHeader("Cookie","JSESSIONID=299571E0E40DA6E9962E41B87A669BBB")
            .addHeader("content-type", "application/json")
            .addHeader("cache-control", "no-cache")
            .build();
    Call call=okHttpClient.newCall(request);

    try {
    
        Response response=call.execute();
        System.out.println(response.body().string());
    } catch (IOException e) {
    
        e.printStackTrace();
    }
}

2.2 封装OKHttp

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class OkHttpUtil {
    

    /**
     * Get请求
     * @param url   URL地址
     * @return  返回结果
     */
    public static String get(String url){
    
        String result=null;
        try {
    
            OkHttpClient okHttpClient=new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = okHttpClient.newCall(request).execute();
            result=response.body().string();
            log.info("Get请求返回:{}",result);
            return result;
        }catch (Exception e){
    
            log.error("OkHttp[Get]请求异常",e);
            return result;
        }
    }

    /**
     * Post请求
     * @param url       URL地址
     * @param params    参数
     * @return  返回结果
     */
    public static String post(String url,Map<String,String> params){
    
        String result=null;
        if (params==null){
    
            params=new HashMap<String, String>();
        }
        try {
    
            OkHttpClient okHttpClient=new OkHttpClient();
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            //添加参数
            log.info("params:{}", JSON.toJSONString(params));
            for (Map.Entry<String,String> map:params.entrySet()){
    
                String key=map.getKey();
                String value;
                if (map.getValue()==null){
    
                    value="";
                }else{
    
                    value=map.getValue();
                }
                formBodyBuilder.add(key,value);
            }
            FormBody formBody =formBodyBuilder.build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            Response response = okHttpClient.newCall(request).execute();
            result=response.body().string();
            log.info("Post请求返回:{}",result);
            return result;
        }catch (Exception e){
    
            log.error("OkHttp[Post]请求异常",e);
            return result;
        }
    }

    /**
     * 上传文件请求(Post请求)
     * @param url       URL地址
     * @param params    文件 key:参数名 value:文件 (可以多文件)
     * @return  返回结果
     */
    public static String upload(String url, Map<String, File> params){
    
        String result=null;
        try {
    
            OkHttpClient okHttpClient=new OkHttpClient();
            MultipartBody.Builder multipartBodyBuilder =new MultipartBody.Builder().setType(MultipartBody.FORM);

            for (Map.Entry<String,File> map:params.entrySet()){
    
                String key=map.getKey();
                File file=map.getValue();
                if (file==null||(file.exists() && file.length() == 0)){
    
                    continue;
                }
                multipartBodyBuilder.addFormDataPart(key,file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"), file));
            }
            RequestBody requestBody =multipartBodyBuilder.build();
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Response response = okHttpClient.newCall(request).execute();
            result=response.body().string();
            log.info("Upload请求返回:{}",result);
            return result;
        }catch (Exception e){
    
            log.error("OkHttp[Upload]请求异常",e);
            return result;
        }
    }

    /**
     * 下载文件请求(Get请求)
     * @param url       URL地址
     * @param savePath  保存路径(包括文件名)
     * @return  文件保存路径
     */
    public static String download(String url,String savePath){
    
        String result=null;
        try {
    
            OkHttpClient okHttpClient=new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = okHttpClient.newCall(request).execute();
            File file=new File(savePath);
            if (!file.getParentFile().exists()){
    
                file.getParentFile().mkdirs();
            }
            BufferedSink sink =Okio.buffer((Okio.sink(file)));
            sink.writeAll(response.body().source());
            sink.flush();
            sink.close();
            result=savePath;
            log.info("Download请求返回:{}",result);
            return result;
        }catch (Exception e){
    
            log.error("OkHttp[Download]请求异常",e);
            return result;
        }
    }

}

2.3 OKHttp的post方式详解

①基本的post请求,包含参数
/**
  * post请求的body中带有参数
  */
 @Test
 public void postWithBody() throws IOException {
    
     //构建请求的body
     RequestBody body = new FormBody.Builder()
             .add("username", "zhangsan")
             .add("password", "123456")
             .build();

     //构建请求
     Request request = new Request.Builder()
             .url(base_url + "testOkHttpByPost")
             .post(body)
             .build();
     Call call = client.newCall(request);
     Response response = call.execute();
     Assert.assertEquals(response.code(), 200);
 }
//post请求的body中带有参数
@PostMapping("/testOkHttpByPost")
public void testOkHttpByPost(HttpServletRequest request) {
    
    Map<String, String[]> parameterMap = request.getParameterMap();
    for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
    
        System.out.println(entry.getKey());
        String[] value = entry.getValue();
        System.out.println(Arrays.toString(value));
    }
}
②post请求带有授权
/**
 * post请求带有授权的
 */
@Test
public void postWithAuth() throws IOException {
    
    String postBody = "test post auth";
    Request request = new Request.Builder()
            .url(base_url + "testOkHttpByAuth")
            .addHeader("Authorization", "Messi")
            .post(RequestBody.create(
                    MediaType.parse("text/x-markdown"), postBody))
            .build();
    Call call = client.newCall(request);
    Response response = call.execute();
    Assert.assertEquals(response.code(), 200);
}
//post请求中带有身份验证
@PostMapping("/testOkHttpByAuth")
public void testOkHttpByAuth(HttpServletRequest request, @RequestBody String text){
    
    String authorization = request.getHeader("Authorization");
    if("Messi".equals(authorization)){
    
        System.out.println("success...");
    }else {
    
        System.out.println("fail....");
    }
    System.out.println(text);//test post auth
}
③post请求中带有json数据
 /**
  * post向请求体中发送json数据
  */
 @Test
 public void postByJson() throws IOException {
    
     String json = "{\n" +
             "    \"username\":\"laowang\",\n" +
             "    \"age\":18\n" +
             "}";
     //为了在请求体中发送json,需要设置媒体类型为application/json
     RequestBody body = RequestBody.create(
             MediaType.parse("application/json"),json);
     Request request = new Request.Builder()
             .url(base_url + "/postByJson")
             .post(body)
             .build();
     Call call = client.newCall(request);
     Response response = call.execute();
     Assert.assertEquals(response.code(), 200);
 }
//post请求体带有json数据
@PostMapping("/postByJson")
public void testOkHttpByJson(@RequestBody String json){
    
    System.out.println(json);
}
④发送Multipart post
/**
 * 发送 Multipart post请求
 */
@Test
public void postByMultipart() throws IOException {
    
    RequestBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", "wangchen")
            .addFormDataPart("password", "123456")
            .addFormDataPart("file", "file.txt",
                    RequestBody.create(MediaType.parse("application/octet-stream"),
                            new File("src/main/resources/text.txt")))
            .build();

    Request request = new Request.Builder()
            .url(base_url + "/postMultipart")
            .post(body)
            .build();

    Call call = client.newCall(request);
    Response response = call.execute();
    Assert.assertEquals(response.code(), 200);
}
//发送Multipart post
@PostMapping("/postMultipart")
public void testOkHttpMultipart(String username, String password, MultipartFile file){
    
    System.out.println(username);
    System.out.println(password);
    String originalFilename = file.getOriginalFilename();
    System.out.println(originalFilename);
}
⑤修改编码格式
 //通过其他方式编码
 //如果我们想使用其他字符编码,我们可以将其作为 MediaType.parse () 的第二个参数传入:
 @Test
 public void postByOtherEncoding(){
    
     String json = "{\n" +
             "    \"username\":\"laowang\",\n" +
             "    \"age\":18\n" +
             "}";
     RequestBody body = RequestBody.create(
             MediaType.parse("application/json;charset=utf-16"), json);

     String charset = body.contentType().charset().displayName();
     Assert.assertEquals(charset, "UTF-16");
 }

2.4 OKHttp发起同步异步请求

2.4.1 同步发送get请求
 /**
  * get请求【同步方式】
  * @param url
  * @return
  */
 public static Response getWithNoParam(String url){
    
     Response result = null;
     try{
    
         //设置5s超时
         OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
         //请求
         Request request = new Request.Builder().url(url).build();
         System.out.println("request.headers() = " + request.headers().toString());
         System.out.println(">>>>>>>>>>>" + request.headers().get("Host"));
         //响应
         Response response = client.newCall(request).execute();
         //获取响应体内容
         result = response;
         return result;
     } catch (Exception e){
    
         log.error("get请求异常:{}", e);
         return result;
     }
 }




/**
 * 同步发送get请求【添加参数】
 * @param url
 * @param paramMap
 * @return
 */
public static Response getWithParams(String url, Map<String, String> paramMap){
    
    Request.Builder requestBuilder = new Request.Builder();
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    String key = "";
    String value = "";
    for(Map.Entry<String, String> entry : paramMap.entrySet()){
    
        key = entry.getKey();
        value = entry.getValue();
        urlBuilder.addQueryParameter(key, value);
    }
    requestBuilder.url(urlBuilder.build());
    Request request = requestBuilder.build();
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
    Call call = client.newCall(request);
    Response response = null;
    try {
    
        response = call.execute();
    } catch (IOException e) {
    
        e.printStackTrace();
    }
    return response;
}
2.4.2 异步发送get请求
/**
 * 异步发起get请求
 * @param url
 */
public static void getByAsync(String url){
    
    OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
    Request request = new Request.Builder().url(url).get().build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
    
        @Override
        public void onFailure(Call call, IOException e) {
    
            //请求失败之后所作操作...
            System.out.println("fail.....");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
    
            //请求成功之后所做操作....异步请求成功之后的回调,例如:txtView.setText(response.body().string ());
            System.out.println(response.body().string());
        }
    });
}

2.5 忽略SSL证书

@Slf4j
public class TestYun {
    
    public static void main(String[] args) {
    
       String url = "http://www.baidu.com";
        //发送get请求
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();
        Request request = new Request.Builder().url(url).get().build();
        ResponseBody body = null;
        try {
    
            body = client.newCall(request).execute().body();
            String string = body.string();
            log.info("res:{}", string);
        } catch (IOException e) {
    
            e.printStackTrace();
        }

    }
    public static SSLSocketFactory createSSLSocketFactory() {
    
        SSLSocketFactory ssfFactory = null;

        try {
    
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null,  new TrustManager[] {
     new TrustAllCerts() }, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
    
        }

        return ssfFactory;
    }


    private static class TrustAllCerts implements X509TrustManager {
    
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];}
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
    
        @Override
        public boolean verify(String hostname, SSLSession session) {
    
            return true;
        }
    }
}

3 使用HttpClient

3.1 发送基本请求

//创建连接[同步连接]
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//    CloseableHttpClient client = HttpClients.createDefault();//创建默认client【与上面没有区别】

//创建连接【异步】
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClientBuilder.create().build();

private String uri_prefix = "http://localhost:8080/";

①get方式

    //get请求
    @Test
    public void testGet() throws IOException {
    
        String url = uri_prefix + "testGet";
        HttpGet httpGet = new HttpGet(url);
        //给请求头设置值【get也可以通过拼接URL来传递参数】
        httpGet.setHeader("token", "fadsofafa");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        System.out.println(response.getEntity());
    }

②put方式

//put请求
@Test
public void testPut() throws IOException {
    
    String api = "testPut";
    String url = uri_prefix + api;
    HttpPut httpPut = new HttpPut(url);
    //要传输的json数据【标准写法应该通过对象传输,然后转换为json串】
    String json = "{\n" +
            "    \"username\":\"laowang\",\n" +
            "    \"age\":18\n" +
            "}";
    //传输json数据,修改request头信息
    httpPut.setHeader("Content-Type", "application/json;charset=utf8");
    //设置传输的json
    httpPut.setEntity(new StringEntity(json, "UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPut);
    System.out.println(EntityUtils.toString(response.getEntity()));
}

③post

//post请求[与put方式无太多区别]
@Test
public void testPost() throws IOException {
    
    String api = "testPost";
    String url = uri_prefix + api;
    HttpPost httpPost = new HttpPost(url);
    String json = "{\n" +
            "    \"username\":\"laowang\",\n" +
            "    \"age\":18\n" +
            "}";
    httpPost.setHeader("Content-Type", "application/json;charset=utf8");
    //设置具体数据
    httpPost.setEntity(new StringEntity(json, "UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    System.out.println(response.getEntity());
}

④delete

//测试delete
@Test
public void testDelete() throws IOException {
    
    String api = "testDelete";
    String url = uri_prefix + api;
    HttpDelete httpDelete = new HttpDelete(url);
    CloseableHttpResponse response = httpClient.execute(httpDelete);
    System.out.println(EntityUtils.toString(response.getEntity()));
}

其他同理

3.2 工具类HttpClientUtils

public class HttpClientUtils {
    

    public static final int connTimeout=10000;
    public static final int readTimeout=10000;
    public static final String charset="UTF-8";
    private static HttpClient client = null;

    static {
    
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
    
        return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
    }

    public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
    
        return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
            SocketTimeoutException, Exception {
    
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
            SocketTimeoutException, Exception {
    
        return postForm(url, params, null, connTimeout, readTimeout);
    }

    public static String get(String url) throws Exception {
    
        return get(url, charset, null, null);
    }

    public static String get(String url, String charset) throws Exception {
    
        return get(url, charset, connTimeout, readTimeout);
    }

    /**
     * 发送一个 Post 请求, 使用指定的字符集编码.
     *
     * @param url
     * @param body RequestBody
     * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
     * @param charset 编码
     * @param connTimeout 建立链接超时时间,毫秒.
     * @param readTimeout 响应超时时间,毫秒.
     * @return ResponseBody, 使用指定的字符集编码.
     * @throws ConnectTimeoutException 建立链接超时异常
     * @throws SocketTimeoutException  响应超时
     * @throws Exception
     */
    public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
            throws ConnectTimeoutException, SocketTimeoutException, Exception {
    
        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
    
            if (StringUtils.isNotBlank(body)) {
    
                HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
                post.setEntity(entity);
            }
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
    
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
    
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());

            HttpResponse res;
            if (url.startsWith("https")) {
    
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
    
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
    
            post.releaseConnection();
            if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
    
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }


    /**
     * 提交form表单
     *
     * @param url
     * @param params
     * @param connTimeout
     * @param readTimeout
     * @return
     * @throws ConnectTimeoutException
     * @throws SocketTimeoutException
     * @throws Exception
     */
    public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
            SocketTimeoutException, Exception {
    

        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        try {
    
            if (params != null && !params.isEmpty()) {
    
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
    
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
                post.setEntity(entity);
            }

            if (headers != null && !headers.isEmpty()) {
    
                for (Entry<String, String> entry : headers.entrySet()) {
    
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
    
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
    
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());
            HttpResponse res = null;
            if (url.startsWith("https")) {
    
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
    
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
        } finally {
    
            post.releaseConnection();
            if (url.startsWith("https") && client != null
                    && client instanceof CloseableHttpClient) {
    
                ((CloseableHttpClient) client).close();
            }
        }
    }

    /**
     * 发送一个 GET 请求
     */
    public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
            throws ConnectTimeoutException,SocketTimeoutException, Exception {
    

        HttpClient client = null;
        HttpGet get = new HttpGet(url);
        String result = "";
        try {
    
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
    
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
    
                customReqConf.setSocketTimeout(readTimeout);
            }
            get.setConfig(customReqConf.build());

            HttpResponse res = null;

            if (url.startsWith("https")) {
    
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
    
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(get);
            }

            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
    
            get.releaseConnection();
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
    
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 从 response 里获取 charset
     */
    @SuppressWarnings("unused")
    private static String getCharsetFromResponse(HttpResponse ressponse) {
    
        // Content-Type:text/html; charset=GBK
        if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
    
            String contentType = ressponse.getEntity().getContentType().getValue();
            if (contentType.contains("charset=")) {
    
                return contentType.substring(contentType.indexOf("charset=") + 8);
            }
        }
        return null;
    }

    /**
     * 创建 SSL连接
     * @return
     * @throws GeneralSecurityException
     */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
    
        try {
    
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
    
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
    

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
    
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl)
                        throws IOException {
    
                }

                @Override
                public void verify(String host, X509Certificate cert)
                        throws SSLException {
    
                }

                @Override
                public void verify(String host, String[] cns,
                                   String[] subjectAlts) throws SSLException {
    
                }
            });
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (GeneralSecurityException e) {
    
            throw e;
        }
    }
}

参考文章:
https://www.jianshu.com/p/7342b7a35ffc
https://www.jianshu.com/p/4a3c585a99f4
使用OkHttp发送POST请求
OkHttp与HttpClient

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_45565886/article/details/127360561

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签