public class httpClientStuParam06Test {
@Test
public void getParam() throws URISyntaxException {
System.out.println("测试httpClient配置");
//1:创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2:设置请求参数 http://yun.itheima.com/search?keys=Java
//创建URIBuilder
URIBuilder uriBuilder = new URIBuilder("http://yun.itheima.com/search");
//设置一个参数,若设置多个参数 uriBuilder.setParameter("keys", "Java").setParameter("login","userName");
uriBuilder.setParameter("keys", "Java").setParameter("login", "张三同学");
HttpGet httpGet = new HttpGet(uriBuilder.build());
System.out.println("http请求信息:"+httpGet); //返回值: http请求信息: GET http://www.itcast.cn HTTP/1.1
//3:设置请求响应的接收变量,如内容为主及必要信息(host,API,HTTP code,响应code,响应时间等等记录)。
CloseableHttpResponse response=null;
try {
response= httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
//把得到响应的载体内容,传递给变量content
String content = EntityUtils.toString(response.getEntity(), "utf8");
//输出响应内容的长度,暂不输出
System.out.println("响应得到内容长度为:"+content.length());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文链接 https://www.cnblogs.com/asplover/p/12486566.html