前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >CloseableHttpClient简单使用实例[通俗易懂]

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

作者头像
全栈程序员站长
发布2022-07-25 21:21:25
发布2022-07-25 21:21:25
9250
举报

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年4月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档