public class HttpUtils { private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); /** * POST 请求 * * @param url 目标地址 * @param expectResponseStatus 期望返回状态 * @param headers 请求头部 * @param bodyMap 请求体 * @return */ public static String doPost(String url, int expectResponseStatus, Map<String, String> headers, Map<String, Object> bodyMap) { HttpPost post = new HttpPost(url); post.addHeader("Content-Type", "application/json;charset=utf-8"); // post.addHeader("Accept", "application/json"); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> entry : headers.entrySet()) { post.setHeader(entry.getKey(), entry.getValue()); } } JSONObject jsonParam = new JSONObject(); for (Map.Entry<String, Object> entry : bodyMap.entrySet()) { jsonParam.put(entry.getKey(), entry.getValue()); } HttpClient client = null; String respnseContent = null; try { StringEntity entity = new StringEntity(jsonParam.toString(), Charset.forName("UTF-8"));//解决中文乱码 // entity.setContentEncoding("utf-8"); // entity.setContentType("application/json"); post.setEntity(entity); client = wrapClient(url); if (client == null) { return null; } HttpResponse response = client.execute(post); respnseContent = analysisResopnseContent(response, expectResponseStatus); //return respnseContent; } catch (UnsupportedEncodingException e) { LoggerUtils.error(LOGGER, "====== UnsupportedEncodingException happened : {} ======", e); } catch (ClientProtocolException e) { LoggerUtils.error(LOGGER, "====== ClientProtocolException happened : {} ======", e); } catch (IOException e) { LoggerUtils.error(LOGGER, "====== IOException happened : {} ======", e); } finally { if (post != null) { post.releaseConnection(); } if (client != null) { client.getConnectionManager().shutdown(); } return respnseContent; } } public static String httpsPostJson(String url, String jsonObject) throws IOException { OkHttpClient client = getUnsafeOkHttpClient(); MediaType mediaType = MediaType.parse("application/json;charset=UTF-8"); RequestBody body = RequestBody.create(mediaType, jsonObject); Request request = new Request.Builder() .url(url) .method("POST", body) .addHeader("Content-Type", "application/json;charset=UTF-8") .addHeader("Set-Cookie","JSESSIONID=A61960CDCDFD1D3CB55F0F60F7CC58DB37628319347FBF5CEB63A70C22D9DFEC; Path=/; Secure; HttpOnly") .build(); // 4 执行请求操作 Response response = client.newCall(request).execute(); String result = response.body().string(); String session=response.header("Set-Cookie"); LOGGER.info("接口返回结果" + session); if(result.replaceAll("null", "\"\"").equals("{\"resultCode\":0}")){ return session; }else{ return null; } } public static OkHttpClient getUnsafeOkHttpClient() { try { // Create a trust manager that does not validate certificate chains final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; // Install the all-trusting trust manager final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); builder.hostnameVerifier((hostname, session) -> true); return builder.build(); } catch (Exception e) { throw new RuntimeException(e); } } public static String analysisResopnseContent(HttpResponse response, int expectResponseStatus) throws IOException { String resopnseContent = null; if (response.getStatusLine().getStatusCode() == expectResponseStatus) { HttpEntity responseEntity = response.getEntity(); resopnseContent = EntityUtils.toString(responseEntity, "utf-8"); } else { LoggerUtils.info(LOGGER, "response status:{}", response.getStatusLine().getStatusCode()); LoggerUtils.info(LOGGER, "response content:{}", EntityUtils.toString(response.getEntity(), "utf-8")); } return resopnseContent; } /** * PUT 请求 * * @param url 目标地址 * @param expectResponseStatus 期望返回状态 * @param headers 请求头部 * @param bodyMap 请求体 * @return */ public static String doPut(String url, int expectResponseStatus, Map<String, String> headers, Map<String, Object> bodyMap) { HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type", "application/json;charset=utf-8"); httpPut.addHeader("Accept", "application/json"); if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPut.setHeader(entry.getKey(), entry.getValue()); } } JSONObject jsonParam = new JSONObject(); for (Map.Entry<String, Object> entry : bodyMap.entrySet()) { jsonParam.put(entry.getKey(), entry.getValue()); } HttpClient client = null; try { StringEntity entity = new StringEntity(jsonParam.toString(), Charset.forName("UTF-8")); entity.setContentEncoding("utf-8");
java http,post请求代码,参数是json, 调用方接口定义参数@RequstBody
于 2021-10-13 14:26:49 首次发布