网络编程 
首页 > 网络编程 > 浏览文章

JSP开发中Apache-HTTPClient 用户验证的实例详解

(编辑:jimmy 日期: 2025/6/26 浏览:3 次 )

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隐藏关键敏感字段信息只显示前后字段的示例
下一篇:Spring 事务隔离与事务传播的详解与对比
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap