欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-13 15:07:46
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 用户验证的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!