后端发送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

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法