【java实战】OKHttp使用--跳过证书请求

【java实战】OKHttp使用–跳过证书请求

一、使用背景

项目过程中需要访问https,是需要加证书访问的,但是可以通过OKhttp进行访问

二、OKHttp加载依赖
<dependency>
           <groupId>com.squareup.okhttp3</groupId>
           <artifactId>okhttp</artifactId>
           <version>4.4.1</version>
       </dependency>
三、使用过程中的方法整理
3.1 json生成
protected static String makeJson(Object object) {
       if (object instanceof String)
           return (String) object;
       return GSON.toJson(object);
   }
3.2 get方法生成查询条件拼接到url
protected static String makeQuery(Object object) {
       String form = makeForm(object);
       if (form.length() == 0)
           return "";
       return "?" + form;
   }

   protected static String makeForm(Object object) {
       if (object == null)
           return "";
       return queryParams(makeFormRecursive(GSON.toJsonTree(object), true));
   }


   private static Map<String, String> makeFormRecursive(JsonElement data, boolean root) {
       Map<String, String> form = new HashMap<>();
       if (data instanceof JsonArray) {
           JsonArray array = data.getAsJsonArray();
           for (int i = 0; i < array.size(); i++) {
               Map<String, String> value = makeFormRecursive(array.get(i), false);
               for (String k : value.keySet()) {
                   form.put("[" + i + "]" + k, value.get(k));
               }
           }
           return form;
       }
       if (data instanceof JsonObject) {
           JsonObject object = data.getAsJsonObject();
           for (String key : object.keySet()) {
               Map<String, String> value = makeFormRecursive(object.get(key), false);
               for (String k : value.keySet()) {
                   if (root) {
                       form.put(key + k, value.get(k));
                   } else {
                       form.put("[" + key + "]" + k, value.get(k));
                   }
               }
           }
           return form;
       }
       if (data instanceof JsonPrimitive) {
           JsonPrimitive primitive = data.getAsJsonPrimitive();
           if (primitive.isBoolean())
               form.put("", String.valueOf(primitive.getAsBoolean()));
           if (primitive.isNumber())
               form.put("", String.valueOf(primitive.getAsInt()));
           if (primitive.isString())
               form.put("", primitive.getAsString());
           return form;
       }
       form.put("", data.toString());
       return form;
   }

   private static String urlEncode(String value) {
       try {
           return URLEncoder.encode(value, "UTF-8");
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       }
       return value;
   }

   private static String queryParams(Map<String, String> params) {
       List<String> p = new ArrayList<>();
       for (String key : params.keySet()) {
           p.add(key + "=" + urlEncode(params.get(key)));
       }
       return String.join("&", p);
   }

3.3 get方法使用
public String get(String url, Map<String, String> header, Map<String, Object> query) {
       String result = null;
       Request request = new Request.Builder()
               .url(url + makeQuery(query))
               .headers(Headers.of(header))
               .get()
               .build();
       Response response = null;
       try {
           response = OKHttpClientBuilder.buildOKHttpClient()
                   .build()
                   .newCall(request)
                   .execute();
           if (response.isSuccessful()) {
               if (response.body() != null) {
                   result =  response.body().string();
               }
           } else {
               response.close();
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
       return result;
   }
3.4 post方法
public String post(String url, Map<String, String> header, Object body) {
       MediaType JSON = MediaType.parse("application/json; charset=utf-8");
       String result = null;
       Request request = new Request.Builder()
               .url(url)
               .headers(Headers.of(header))
               .post(RequestBody.create(JSON, body == null ? null : makeJson(body)))
               .build();
       Response response = null;
       try {
           response = OKHttpClientBuilder.buildOKHttpClient()
                   .build()
                   .newCall(request)
                   .execute();
           if (response.isSuccessful()) {
               if (response.body() != null) {
                   result = response.body().string();
               }
           } else {
               response.close();
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
       return result;
   }
3.5 delete方法
public String delete(String url, Map<String, String> header, Object body) {
       MediaType JSON = MediaType.parse("application/json; charset=utf-8");
       String result = null;
       Request request = new Request.Builder()
               .url(url)
               .headers(Headers.of(header))
               .delete(RequestBody.create(JSON, body == null ? null : makeJson(body)))
               .build();
       Response response = null;
       try {
           response = OKHttpClientBuilder.buildOKHttpClient()
                   .build()
                   .newCall(request)
                   .execute();
           if (response.isSuccessful()) {
               if (response.body() != null) {
                   result =  response.body().string();
               }
           } else {
               response.close();
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
       return result;
   }
四、完整代码
package com.awifi.cloudnative.container.kubetelecom.provider.service.impl;

import com.awifi.cloudnative.container.kubetelecom.provider.rancher.OKHttpClientBuilder;
import com.awifi.cloudnative.container.kubetelecom.provider.service.RancherClientService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @ClassName RancherClientServiceImpl
* @Description TODO
* @Author 张鑫
* @Date 2022/1/5
* @Version 1.0
**/
@Service
@Slf4j
public class RancherClientServiceImpl implements RancherClientService {
   public static final Gson GSON = new GsonBuilder().create();

   @Override
   public String get(String url, Map<String, String> header, Map<String, Object> query) {
       String result = null;
       Request request = new Request.Builder()
               .url(url + makeQuery(query))
               .headers(Headers.of(header))
               .get()
               .build();
       Response response = null;
       try {
           response = OKHttpClientBuilder.buildOKHttpClient()
                   .build()
                   .newCall(request)
                   .execute();
           if (response.isSuccessful()) {
               if (response.body() != null) {
                   result =  response.body().string();
               }
           } else {
               response.close();
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
       return result;
   }

   @Override
   public String post(String url, Map<String, String> header, Object body) {
       MediaType JSON = MediaType.parse("application/json; charset=utf-8");
       String result = null;
       Request request = new Request.Builder()
               .url(url)
               .headers(Headers.of(header))
               .post(RequestBody.create(JSON, body == null ? null : makeJson(body)))
               .build();
       Response response = null;
       try {
           response = OKHttpClientBuilder.buildOKHttpClient()
                   .build()
                   .newCall(request)
                   .execute();
           if (response.isSuccessful()) {
               if (response.body() != null) {
                   result = response.body().string();
               }
           } else {
               response.close();
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
       return result;
   }

   @Override
   public String delete(String url, Map<String, String> header, Object body) {
       MediaType JSON = MediaType.parse("application/json; charset=utf-8");
       String result = null;
       Request request = new Request.Builder()
               .url(url)
               .headers(Headers.of(header))
               .delete(RequestBody.create(JSON, body == null ? null : makeJson(body)))
               .build();
       Response response = null;
       try {
           response = OKHttpClientBuilder.buildOKHttpClient()
                   .build()
                   .newCall(request)
                   .execute();
           if (response.isSuccessful()) {
               if (response.body() != null) {
                   result =  response.body().string();
               }
           } else {
               response.close();
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
       return result;
   }

   protected static String makeJson(Object object) {
       if (object instanceof String)
           return (String) object;
       return GSON.toJson(object);
   }

   protected static String makeQuery(Object object) {
       String form = makeForm(object);
       if (form.length() == 0)
           return "";
       return "?" + form;
   }

   protected static String makeForm(Object object) {
       if (object == null)
           return "";
       return queryParams(makeFormRecursive(GSON.toJsonTree(object), true));
   }


   private static Map<String, String> makeFormRecursive(JsonElement data, boolean root) {
       Map<String, String> form = new HashMap<>();
       if (data instanceof JsonArray) {
           JsonArray array = data.getAsJsonArray();
           for (int i = 0; i < array.size(); i++) {
               Map<String, String> value = makeFormRecursive(array.get(i), false);
               for (String k : value.keySet()) {
                   form.put("[" + i + "]" + k, value.get(k));
               }
           }
           return form;
       }
       if (data instanceof JsonObject) {
           JsonObject object = data.getAsJsonObject();
           for (String key : object.keySet()) {
               Map<String, String> value = makeFormRecursive(object.get(key), false);
               for (String k : value.keySet()) {
                   if (root) {
                       form.put(key + k, value.get(k));
                   } else {
                       form.put("[" + key + "]" + k, value.get(k));
                   }
               }
           }
           return form;
       }
       if (data instanceof JsonPrimitive) {
           JsonPrimitive primitive = data.getAsJsonPrimitive();
           if (primitive.isBoolean())
               form.put("", String.valueOf(primitive.getAsBoolean()));
           if (primitive.isNumber())
               form.put("", String.valueOf(primitive.getAsInt()));
           if (primitive.isString())
               form.put("", primitive.getAsString());
           return form;
       }
       form.put("", data.toString());
       return form;
   }

   private static String urlEncode(String value) {
       try {
           return URLEncoder.encode(value, "UTF-8");
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       }
       return value;
   }

   private static String queryParams(Map<String, String> params) {
       List<String> p = new ArrayList<>();
       for (String key : params.keySet()) {
           p.add(key + "=" + urlEncode(params.get(key)));
       }
       return String.join("&", p);
   }

}

使用okhttp-4.7.2.jar进行https请求时,我们可以通过以下方法来跳过证书请求: 1. 创建自定义的TrustManager:首先,我们需要创建一个自定义的TrustManager来处理证书验证。这个TrustManager可以继承X509TrustManager,并实现其中的方法。 ```java class MyTrustManager 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]; } } ``` 2. 创建自定义的SSLContext:然后,我们需要使用自定义的TrustManager创建一个SSLContext。 ```java SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom()); ``` 3. 将自定义的SSLContext应用到OkHttpClient:接下来,我们需要通过OkHttpClient.Builder的sslSocketFactory()方法将自定义的SSLContext应用到OkHttpClient中。 ```java OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory(), new MyTrustManager()) .build(); ``` 现在,我们可以使用这个配置好的OkHttpClient来发送https请求了。在这个过程中,我们会跳过证书的验证。 需要注意的是,跳过证书验证存在安全风险,因为这意味着你的应用将接受任何证书,包括无效或伪造的证书。所以,在实际使用中,应该谨慎考虑是否需要跳过证书验证,以保证数据的安全性。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值