JSP开发中Apache-HTTPClient 用户验证的实例详解前言:在微服务框架之外的系统中,我们经常会遇到使用httpClient进行接口调用的问题,除了进行白名单的设置,很多时候我们需要在接口调用的时候需要身份认证。翻了一下官方文档,解决方法很多,但
JSP开发中Apache-HTTPClient 用户验证的实例详解
前言:
在微服务框架之外的系统中,我们经常会遇到使用httpClient进行接口调用的问题,除了进行白名单的设置,很多时候我们需要在接口调用的时候需要身份认证。翻了一下官方文档,解决方法很多,但是都不太符合实际业务场景,这里提供一种简单粗暴的解决方法。
解决方法:利用请求头,将验证信息保存起来。
实现代码:
public class HttpClientUtils {
protected static final Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
private static final String AUTHENKEY = "Authorization";
private static final String BASICKEY = "Basic ";
public static String getConnect(String url,String username,String password) {
CloseableHttpResponse response = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
Base64 token = new Base64();
String authenticationEncoding = token.encodeAsString(new String(username + ":" + password).getBytes());
httpGet.setHeader(AUTHENKEY, BASICKEY + authenticationEncoding);
String responseContent = "";
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
LOG.error(e.toString());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOG.error(e.toString());
}
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
LOG.error(e.toString());
}
}
}
return responseContent;
}
}
以上就是Apache-HTTPClient 用户验证的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
沃梦达教程
本文标题为:JSP开发中Apache-HTTPClient 用户验证的实例详解


猜你喜欢
- 深入了解Spring的事务传播机制 2023-06-02
- JSP 制作验证码的实例详解 2023-07-30
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java实现顺序表的操作详解 2023-05-19
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- JSP页面间传值问题实例简析 2023-08-03
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Java中的日期时间处理及格式化处理 2023-04-18