java httpclient basic授权

来源:互联网 发布:查找重复删除知乎 编辑:程序博客网 时间:2024/06/07 23:01
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



0 0
原创粉丝点击