最近工作中,需要用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