主页 > 知识库 > JSP开发中Apache-HTTPClient 用户验证的实例详解

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

热门标签:服务器配置 Linux服务器 电子围栏 阿里云 银行业务 科大讯飞语音识别系统 团购网站 Mysql连接数设置

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 开发之hibernate配置二级缓存的方法
  • Jsp+Servlet实现购物车功能
  • java JSP开发之Spring中Bean的使用
  • JSP 开发之Spring Security详解
  • JSP制作简单登录界面实例
  • jsp页面验证码完整实例
  • JSP Spring防止用户重复登录的实现方法
  • JSP中springmvc配置validator的注意事项

标签:枣庄 广元 江苏 衢州 蚌埠 萍乡 衡水 大理

巨人网络通讯声明:本文标题《JSP开发中Apache-HTTPClient 用户验证的实例详解》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266