文章目录
【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); } }