携带参数发送httpClient (get)请求,亲测有效。
第一步引入httpClient依赖
第二步上代码
@Test
public void doHttpClientTest(){
// 获得Http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 参数
StringBuffer params= new StringBuffer();
try{
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
params.append("name="+ URLEncoder.encode("liujun", "utf-8"));
params.append("&");
params.append("age=24");
} catch(UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 创建Get请求
HttpGet httpGet= new HttpGet("http://localhost:8888/doGetHttpClintControllerTwo" + "?" + params);
httpGet.setHeader("Content-Type", "application/json;charset=utf8");
// 响应模型
CloseableHttpResponse response= null;
try{
// 由客户端执行(发送)Get请求
response= httpClient.execute(httpGet);
// 配置信息
RequestConfig requestConfig= RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
//response.addHeader("Accept-Encoding","gzip, deflate");
// 从响应模型中获取响应实体
HttpEntity responseEntity= response.getEntity();
System.out.println("响应状态为:"+ response.getStatusLine());
if(responseEntity != null) {
System.out.println("响应内容长度为:"+ responseEntity.getContentLength());
System.out.println("响应内容为:"+ EntityUtils.toString(responseEntity,"utf-8"));
}
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(ParseException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally{
try{
// 释放资源
if(httpClient != null) {
httpClient.close();
}
if(response != null) {
response.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
第三步对应接收事例
@Controller
public class doGetController {
@RequestMapping("doGetHttpClintControllerTwo")
@ResponseBody
public String doGetHttpClintControllerTwo(String name, Integer age) {
String code="没想到"+name+"都"+age+"岁了";
return code;
}
}