package com.telpo.dipperposition.common; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.text.MessageFormat; import java.util.Iterator; import java.util.Map; import java.util.Objects; /** * @program: DataPushServer * @description: okhttp工具类 * @author: linwl * @create: 2020-07-17 15:43 */ @Slf4j @Component public class OkHttpUtil { @Autowired private OkHttpClient okHttpClient; public static OkHttpUtil okHttpUtil; @PostConstruct public void init() { okHttpUtil = this; } /** * 根据map获取get请求参数 * * @param queries * @return */ public StringBuffer getQueryString(String url, Map queries) { StringBuffer sb = new StringBuffer(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); if (firstFlag) { sb.append("?" + entry.getKey() + "=" + entry.getValue()); firstFlag = false; } else { sb.append("&" + entry.getKey() + "=" + entry.getValue()); } } } return sb; } /** * get * * @param url 请求的url * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null * @return */ public String get(String url, Map queries) { StringBuffer sb = getQueryString(url, queries); Request request = new Request.Builder().url(sb.toString()).build(); log.debug(MessageFormat.format("发送Get to url<{0}>,参数为:{1}", url, queries)); return execNewCall(request); } /** * post * * @param url 请求的url * @param params post form 提交的参数 * @return */ public String postFormParams(String url, Map params) { FormBody.Builder builder = new FormBody.Builder(); // 添加参数 if (params != null && params.keySet().size() > 0) { for (String key : params.keySet()) { builder.add(key, params.get(key)); } } log.debug(MessageFormat.format("发送post from to url<{0}>,参数为:{1}", url, params)); Request request = new Request.Builder().url(url).post(builder.build()).build(); return execNewCall(request); } /** Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一:请求Url 参数二:请求的JSON 参数三:请求回调 */ public String postJsonParams(String url, String jsonParams) { RequestBody requestBody = RequestBody.create(jsonParams, MediaType.parse("application/json; charset=utf-8")); Request request = new Request.Builder().url(url).post(requestBody).build(); log.debug(MessageFormat.format("发送post json to url<{0}>,参数为:{1}", url, jsonParams)); return execNewCall(request); } /** Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一:请求Url 参数二:请求的JSON 参数三:请求回调 */ public String getJsonParams(String url, String jsonParams) { Request request = new Request.Builder().url(url).addHeader("application/json","charset=utf-8").build(); log.debug(MessageFormat.format("get json to url<{0}>", url)); return execNewCall(request); } /** Post请求发送xml数据.... 参数一:请求Url 参数二:请求的xmlString 参数三:请求回调 */ public String postXmlParams(String url, String xml) { RequestBody requestBody = RequestBody.create(xml, MediaType.parse("application/xml; charset=utf-8")); Request request = new Request.Builder().url(url).post(requestBody).build(); log.debug(MessageFormat.format("发送post xml to url<{0}>,参数为:{1}", url, xml)); return execNewCall(request); } /** * 调用okhttp的newCall方法 * * @param request * @return */ private String execNewCall(Request request) { try (Response response = okHttpClient.newCall(request).execute()) { if (response.isSuccessful()) { return Objects.requireNonNull(response.body()).string(); } } catch (Exception e) { log.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e)); } return "FAIL"; } /** * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} 参数一:请求Url 参数二:请求的JSON 参数三:请求回调 */ public String postJsonParamsWithToken(String url, String token, String jsonParams) { RequestBody requestBody = RequestBody.create(jsonParams, MediaType.parse("application/json; charset=utf-8")); Request request = new Request.Builder().url(url). addHeader("Authorization", token).post(requestBody).build(); log.debug(MessageFormat.format("发送post json to url<{0}>,参数为:{1}", url, jsonParams)); return execNewCall(request); } public JSONObject postRequestWithJson(String url, String accessToken, JSONObject postData) { String postResult; if (ObjectUtils.isNotEmpty(accessToken)) { postResult = postJsonParamsWithToken(url, accessToken, JSONObject.toJSONString(postData)); } else { postResult = postJsonParams(url, JSONObject.toJSONString(postData)); } if (postResult == null) { log.error("访问错误"); return null; } else { log.debug(postResult); if(("FAIL").equals(postResult.toString())) { JSONObject object = new JSONObject(); object.put("result", "FAIL"); return object; } else { return JSONObject.parseObject(postResult); } } } }