详解JSP开发中Apache-HTTPClient 用户验证的方法
来源:爱站网时间:2019-11-30编辑:网友分享
在开发程序的过程中,我们经常遇到调用接口的问题,很多时候我们还需要在调用接口时进行身份验证,今天就让爱站技术频道小编和大家详解JSP开发中Apache-HTTPClient 用户验证的方法,希望对你有所帮助。
在开发程序的过程中,我们经常遇到调用接口的问题,很多时候我们还需要在调用接口时进行身份验证,今天就让爱站技术频道小编和大家详解JSP开发中Apache-HTTPClient 用户验证的方法,希望对你有所帮助。
详解JSP开发中Apache-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;
}
}
本文是爱站技术频道小编给大家带来的详解JSP开发中Apache-HTTPClient 用户验证的方法,相信大家都有所了解,想要学习到更多的专业知识,欢迎关注爱站技术频道小编为大家带来的推荐。
