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 用户验证的实例详解
基础教程推荐
猜你喜欢
- 运用El表达式截取字符串/获取list的长度实例 2023-08-01
- Java编写实现窗体程序显示日历 2023-01-02
- JavaWeb 实现验证码功能(demo) 2024-04-14
- Java中EnvironmentAware 接口的作用 2023-01-23
- 使用Java和WebSocket实现网页聊天室实例代码 2024-02-25
- 是否适合从javabean类更新数据库? 2023-11-04
- 深入理解约瑟夫环的数学优化方法 2024-03-07
- springboot下使用shiro自定义filter的个人经验分享 2024-02-27
- JSP 动态树的实现 2023-12-17
- Java+mysql实现学籍管理系统 2023-03-16
