方法一、使用springboot框间自带的Http的工具类RestTemplate。
RestTemplate为springframework中自带的处理Http的工具类。
具体用法
请求的接口
@RestController
@RequestMapping("/index")
public class MyController {
@PostMapping("/testPost")
public Map testPost(@RequestBody Map map) {
Map mm = new HashMap<>();
mm.put("学号", map.get("sno"));
mm.put("姓名", map.get("sname"));
mm.put("年龄", map.get("age"));
mm.put("性别", map.get("sex"));
mm.put("班级", map.get("sclass"));
return mm;
}
@GetMapping("/testGet")
public Student testGet(@RequestParam String sno,
@RequestParam String sname,
@RequestParam String age,
@RequestParam String sex,
@RequestParam String sclass) {
Student student = new Student(Integer.parseInt(sno), sname, Integer.parseInt(age), sex, sclass);
return student;
}
}
Get和Post请求
@Test
public void testExchange_post() {
Student student = new Student(20160004, "李四", 20, "男", "2016222");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
//headerName必须是英文,headerValue可以有中文
//请求头会封装一些像token这些信息,用于作为调接口的鉴权
httpHeaders.add("studentInfo", "个人信息");
HttpEntity httpEntity = new HttpEntity<>(student, httpHeaders);
System.out.println("httpEntity的请求头为:" + httpEntity.getHeaders());
System.out.println("httpEntity的请求体为:" + httpEntity.getBody());
ResponseEntity
方法二、使用apache的httpclient工具类
org.apache.httpcomponents
httpclient
4.5.13
com.alibaba
fastjson
1.2.78
@Test
public void testHttpClient_get() throws URISyntaxException, IOException {
// 获得Http客户端
HttpClient httpClient = HttpClientBuilder.create().build();
Student student = new Student(20160004, "李四", 20, "男", "2016222");
// 将参数放入键值对类NameValuePair中,再放入集合中
List params = new ArrayList<>();
params.add(new BasicNameValuePair("sno", String.valueOf(student.getSno())));
params.add(new BasicNameValuePair("sname", student.getSname()));
params.add(new BasicNameValuePair("age", String.valueOf(student.getAge())));
params.add(new BasicNameValuePair("sex", student.getSex()));
params.add(new BasicNameValuePair("sclass", student.getSclass()));
URI uri = new URIBuilder().setScheme("http").setHost("localhost")
.setPort(8080).setPath("/index/testGet")
.setParameters(params).build();
// 创建Get请求
HttpGet httpGet = new HttpGet(uri);
// 响应模型
HttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} finally {
// try {
// // 释放资源
// if (httpClient != null) {
// httpClient.close();
// }
// if (response != null) {
// response.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//CloseableHttpClient HttpClient HttpResponse HttpServletResponse
}
}
@Test
public void testHttpClient_post() throws URISyntaxException, IOException {
// 获得Http客户端
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/index/testPost");
Student student = new Student(20160004, "李四", 20, "男", "2016222");
// 我这里利用阿里的fastjson,将Object转换为json字符串;
// (需要导入com.alibaba.fastjson.JSON包)
String jsonString = JSON.toJSONString(student);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 响应模型
HttpResponse response = null;
HttpServletResponse httpServletResponse = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException 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();
// }
}
}
参考资料