import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; --------------------------------------- //配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书) SSLContext sslContext = null; try { sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }).build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } //创建httpClient CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext). setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); //创建 POST请求对象 HttpPost post = new HttpPost(url); //请求参数设置 JSonObject param = new JSonObject(); param.put("name", "A"); param.put("value", "a"); String jsonParam = param.toString(); post.setEntity(new StringEntity(jsonParam, "UTF-8")); //请求头设置 post.addHeader("Content-Type", "application/json; charset=utf-8"); post.addHeader("Host", URL_HOST); //请求超时时间设置 post.setConfig(RequestConfig.custom() // 连接超时时间 .setConnectTimeout(5000) // 请求超时时间 .setConnectionRequestTimeout(5000) // Socket读取超时时间 .setSocketTimeout(5000) // 是否允许重定向 .setRedirectsEnabled(false) .build()); //发送请求 CloseableHttpResponse response = null; try { response = client.execute(post); } catch (IOException e) { e.printStackTrace(); log.error("request error. "); return responseDto; } //处理请求结果 response
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)