1.HttpClient工具类
public class HttpClientUtils {
/**
带请求头的get请求
**/
public static String doGet(String url) throws IOException {
CloseableHttpClient client=null;
CloseableHttpResponse response=null;
try {
//1.创建httplient
client = HttpClients.createDefault();
//2.创建httpget
HttpGet httpGet = new HttpGet(url);
//3.添加请求头
httpGet.setHeader(new BasicHeader("k", "v"));
//4.执行请求
response = client.execute(httpGet);
//5.获取响应头
int statusCode = response.getStatusLine().getStatusCode();
if (200 == statusCode) {
//6.获取响应实体
return EntityUtils.toString(response.getEntity(), "utf-8");
}
} finally {
//关流相关
response.close();
client.close();
}
return null;
}
/**
带实体参数和请求头的post请求
**/
public static String doPost(String url) throws IOException {
CloseableHttpClient client=null;
CloseableHttpResponse response=null;
try {
//1.创建httplient
client = HttpClients.createDefault();
//2.创建httppost
HttpPost httpPost = new HttpPost(url);
//3.添加请求头,和请求体
httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=utf-8"));
String jsonParam="{\"username\":\"123456\",\"password\":\"123456\"}";
httpPost.setEntity(new StringEntity(jsonParam, ContentType.APPLICATION_JSON));
//4.执行请求
response = client.execute(httpPost);
//5.获取响应头
int statusCode = response.getStatusLine().getStatusCode();
if (200 == statusCode) {
//6.获取响应实体
return EntityUtils.toString(response.getEntity(), "utf-8");
}
}finally {
//关流相关
response.close();
client.close();
}
return null;
}
2.注意点
注意点1:
post请求添加请求体参数:httpPost.setEntity(new StringEntity(jsonParam, ContentType.APPLICATION_JSON));
这儿默认的请求体类型为:httpPost.setEntity(new StringEntity(jsonParam)); text/plain:普通文本类型
用哪种请求体类型取决于接受参数体Controller
text/plain vs application/json
//这种类型接受的请求体类型applicatin/json
@RequestMapping("back")
public String goToBackIndex(@RequestBody Map<String,String> jsonpObject){
System.out.println("跳到后台添加首页");
return "addProduct";
}
@RequestMapping("back")
public String goToBackIndex(@RequestBody JsonObject jsonpObject){
System.out.println("跳到后台添加首页");
return "addProduct";
}
@RequestMapping("back")
public String goToBackIndex(@RequestBody User jsonpObject){
System.out.println("跳到后台添加首页");
return "addProduct";
}
//这种类型接受的请求体类型text/plain
@RequestMapping("back")
public String goToBackIndex(@RequestBody String jsonpObject){
System.out.println("跳到后台添加首页");
return "addProduct";
}
注意点2:
1.发送json数据时,要么用 JSONObject.toJSONString(object)将对象直接转为json字符串
2.要么在自定义json字符串的时候,要用转义字符:如:
String jsonParam="{\"username\":\"123456\",\"password\":\"123456\"}";
//这种形式无法解析。
String jsonParam="{'username':'123456','password':'123456'}";