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 用户验证的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
本文转载自微信公众号「SH的全栈笔记」,作者SH。转载本文请联系SH的全栈笔记公...
本文转载自微信公众号「SQL数据库」,作者丶平凡世界 。转载本文请联系开发公众...
大家好,我是狂聊君。 今天来聊一聊 Mysql 缓存池原理。 提纲附上,话不多说,直...
本文实例讲述了AJAX+Servlet实现的数据处理显示功能。分享给大家供大家参考,具...
问题:我们在做flex的开发中,如果用到别人搭建好的框架,而别人的server名称往...
前言 项目开发中不管是前台还是后台都会遇到烦人的null,数据库表中字段允许空值...
在Flash Player 10.1及以上版本中,adobe新增了全局错误处理程序UncaughtErrorEv...
idea官方推送了2020.2.4版本的更新,那么大家最关心的问题来了,之前激活idea202...
CKeditor,以前叫FCKeditor,已经使用过好多年了,功能自然没的说。最近升级到3....
来源:DeepenStudy 漏洞文件:js.asp % Dimoblog setoblog=newclass_sys oblog.a...