您的位置:首页 > 理论基础 > 计算机网络

java httpclient basic授权

2015-08-31 16:51 741 查看
private static void test2() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
String url_str = "http://192.168.1.123:8080/api/v1/clusters/test";
// 用户名:密码
String encoding = new String(Base64.encodeBase64(StringUtils.getBytesUtf8("admin:admin")));
try {
HttpGet httpget = new HttpGet(url_str);
// 向header中设置参数
httpget.addHeader("Authorization", "Basic " + encoding);
CloseableHttpResponse response = httpclient.execute(httpget);
int status = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == status) {
HttpEntity entity = response.getEntity();
if (null == entity) {
return;
}
// Document doc = Jsoup.parse(entity.getContent(), "UTF-8", ""); 可直接用jsoup接收为网页
// entity.getContent内容流, 该api返回的是json字符串
BufferedReader isr = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = isr.readLine()) != null) {
sb.append(line);
}
// 接口返回的是json数据
JSONObject objs = new JSONObject(sb.toString());
System.out.println(objs.toString());
// TODO 根据业务需要处理数据
}
} finally {
httpclient.close();
}
}


这里的httpclient版本是4.5,相关jar包如下:

httpclient-4.5.jar

httpcore-4.4.1.jar

commons-logging-1.1.3.jar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  basic httpclient