Created on 17/9/3 13:57 星期日. @author sd
| 28 | * @author sd |
| 29 | */ |
| 30 | public class ToolSendHttp { |
| 31 | |
| 32 | private static final Logger log = LoggerFactory.getLogger(ToolSendHttp.class); |
| 33 | |
| 34 | public static HttpReceive get(String url) { |
| 35 | return send(HttpSend.of(url).setMethod(HttpMethod.GET)); |
| 36 | } |
| 37 | |
| 38 | public static HttpReceive post(String url) { |
| 39 | return send(HttpSend.of(url).setMethod(HttpMethod.POST)); |
| 40 | } |
| 41 | |
| 42 | public static HttpReceive post(String url, Map<String, Object> params) { |
| 43 | return send(HttpSend.of(url, params).setMethod(HttpMethod.POST)); |
| 44 | } |
| 45 | |
| 46 | public static HttpReceive send(HttpSend httpSend) { |
| 47 | return send(httpSend, ToolHttpBuilder.getDefaultClient()); |
| 48 | } |
| 49 | |
| 50 | public static HttpReceive send(HttpSend httpSend, OkHttpClient.Builder okHttpClientBuilder) { |
| 51 | return send(httpSend, okHttpClientBuilder.build()); |
| 52 | } |
| 53 | |
| 54 | public static HttpReceive send(HttpSend httpSend, OkHttpClient okHttpClient) { |
| 55 | final HttpReceive httpReceive = new HttpReceive(); |
| 56 | httpReceive.setHaveError(true); |
| 57 | try { |
| 58 | Request request = convertRequest(httpSend); |
| 59 | Call call = okHttpClient.newCall(request); |
| 60 | Response response = call.execute(); |
| 61 | ResponseBody body = response.body(); |
| 62 | |
| 63 | if (body == null) { |
| 64 | throw new HttpException("发送http失败,响应体为空"); |
| 65 | } |
| 66 | |
| 67 | final Map<String, String> responseHeaders = Maps.newHashMap(); |
| 68 | if (httpSend.getNeedReceiveHeaders()) { |
| 69 | final Headers headers = response.headers(); |
| 70 | final Set<String> headerNameSet = headers.names(); |
| 71 | headerNameSet.forEach(oneHeaderName -> { |
| 72 | final String oneHeaderValue = headers.get(oneHeaderName); |
| 73 | responseHeaders.put(oneHeaderName, oneHeaderValue); |
| 74 | }); |
| 75 | } |
| 76 | |
| 77 | int responseStatusCode = response.code(); |
| 78 | if (responseStatusCode != 200) { |
| 79 | throw new HttpException("本次请求响应码不是200,是" + responseStatusCode); |
| 80 | } |
| 81 | |
| 82 | String responseBody = body.string(); |
| 83 | if (log.isDebugEnabled()) { |
| 84 | log.debug(responseBody); |
| 85 | } |
| 86 | httpReceive.setResponseBody(responseBody) |
| 87 | .setHaveError(false) |
nothing calls this directly
no outgoing calls
no test coverage detected