java http basic_httpclient处理http basic认证

最近工作中,需要用http请求访问一个带用户认证的接口,花了点时间了解了下,直接上代码:

private static ResponseResult doHttpPostForJsonWithAuth(String url, Map headers,

String json, String encoding, String username, String password) {

HttpPost httpPost = new HttpPost(url);

try {

// Post请求

if (null == headers) {

headers = new HashMap<>();

}

if(headers.size() == 0) {

headers.put("Accept", "application/json");

headers.put("accept-charset", encoding);

headers.put("Content-Type", "application/json; charset=UTF-8");

}

httpPost.setHeaders(assemblyHeader(headers));

// 设置参数

if (StringUtils.isNotBlank(json)) {

httpPost.setEntity(new StringEntity(json, encoding));

}

//生成httpclient

DefaultHttpClient httpClient = url.startsWith("https")

? (DefaultHttpClient)createHttpsClient() : (DefaultHttpClient)createHttpClient();

//处理认证

URL netUrl = new URL(url);

HttpHost targetHost = new HttpHost(netUrl.getHost(), netUrl.getPort(), netUrl.getProtocol());

httpClient.getCredentialsProvider().setCredentials(new AuthScope(targetHost),

new UsernamePasswordCredentials(username, password));

//创建 AuthCache 对象

AuthCache authCache = new BasicAuthCache();

//创建 BasicScheme,并把它添加到 auth cache中

BasicScheme basicAuth = new BasicScheme();

authCache.put(targetHost, basicAuth);

//把AutoCache添加到上下文中

BasicHttpContext httpContext = new BasicHttpContext();

httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

long t1 = System.currentTimeMillis();

// 发送请求,除了httpPost外, 还需要带上host、httpContext

HttpResponse httpresponse = httpClient.execute(targetHost, httpPost, httpContext);

StatusLine statusLine = httpresponse.getStatusLine();

// 获取返回数据

HttpEntity entity = httpresponse.getEntity();

String body = EntityUtils.toString(entity);

EntityUtils.consumeQuietly(entity);

long time = System.currentTimeMillis() - t1;

logger.info("post url=" + url + ", paramters="+json+", time=" + time + " ms");

return new ResponseResult(statusLine.getStatusCode(),statusLine.getReasonPhrase(),body);

} catch (ParseException e) {

throw new RuntimeException("parse error for url:" + url, e);

} catch (UnsupportedEncodingException e) {

throw new RuntimeException("bad encoding:" + encoding, e);

} catch (IOException e) {

throw new RuntimeException("error for url:" + url, e);

}finally{

httpPost.releaseConnection();

}

}

以上代码在httpclient 4.2.5版本下验证通过。 apache的httpclient有commons-httpclient与httpclient,本文代码在httpclient-4.2.5下运行无误,jar包对应的maven引入为:

org.apache.httpcomponents

httpclient

4.2.5

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值