CloseableHttpClient简单使用实例[通俗易懂]

2022-07-25 21:21:25 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; 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.client.protocol.HttpClientContext; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.apache.http.ssl.SSLContextBuilder; import org.apache.tomcat.util.codec.binary.Base64;

import com.alibaba.fastjson.JSONObject;

/** * @author zxs * */ public class DoubleRecordService extends HttpServlet{ /** * */ private static final long serialVersionUID = 517441780092540387L; static String httpProtocol = 请求协议; static String username = 账号”; static String password = 账号对应的密码;(本文使用md5解密后登陆) static String ip = “服务地址”; static int port = 服务端口; static HttpHost target = null; static CloseableHttpClient httpSSlClient = null; /** * 获取受信任httpClient * * @return */ public static CloseableHttpClient createSSLClientDefault() { if (target == null) target = new HttpHost(ip, port, httpProtocol); if (httpSSlClient != null) return httpSSlClient; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, GetMD5.GetMD5Code(password))); SSLContext sslContext;

try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { “TLSv1.2” }, null, new NoopHostnameVerifier()); httpSSlClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credsProvider) .build(); return httpSSlClient; } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return null; } /** * @param jsonObject * @return * @throws ClientProtocolException * @throws IOException */ public static String singleCheck(JSONObject jsonObject) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = createSSLClientDefault(); String data = null; try { HttpClientContext localContext = HttpClientContext.create(); HttpPost httpPost = new HttpPost(httpProtocol “://” ip “:” port “/join/singleCheck”); System.out.println(httpProtocol “://” ip “:” port “/join/singleCheck”); RequestConfig config = RequestConfig.custom().setConnectTimeout(50000).setSocketTimeout(50000).build(); httpPost.setConfig(config); httpPost.setHeader(HTTP.TARGET_HOST,”相应ip地址”); String body = jsonObject.toJSONString(); System.out.println(“参数:” body); httpPost.setHeader(“Content-Type”, “application/json”); StringEntity stringEntity = new StringEntity(body, “UTF-8”);// 解决中文乱码问题 stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, “application/json;charset=utf8”)); httpPost.setEntity(stringEntity); CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext); try { StatusLine tLine = response.getStatusLine(); System.out.println(tLine); HttpEntity entity = response.getEntity(); data = IOUtils.toString(entity.getContent(), “UTF-8”); System.out.println(data); } finally { response.close(); } } finally { // httpclient.close(); } return data; } /** * 构造Basic Auth认证头信息 * * @return */ private String getHeader() { String auth = username “:” GetMD5.GetMD5Code(password); byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName(“US-ASCII”))); String authHeader = “Basic ” new String(encodedAuth); return authHeader; } }

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127773.html原文链接:https://javaforall.cn

0 人点赞