示例地址
1、发送
get
请求
/**
* @return
*/
public String getToken(){
RestTemplate client = new RestTemplate();
StringBuilder sb = new StringBuilder("192.168.35.10");
sb.append("/api/v4/oauth/token?");
//添加应用编号参数
sb.append("client_token punctuation">).append("#123qwer");
String template = client.getForObject(sb.toString(), String.class);
JSONObject jsonObject = JSONObject.parseObject(template);
if ((Integer)jsonObject.get("code") == 200){
String token = (String) jsonObject.getJSONObject("data").get("access_token");
return token;
}
return "";
}
2、发送
post
请求,Payload提交和表单提交两种示例
- 使用Payload提交,即远程接口添加了
@RequestBody
注解接收参数
public void testUrl() {
String url = "http://192.168.35.12:7060/users";
//往请求体添加参数
JSONObject postData = new JSONObject();
postData.put("userId", "yangfanTest1");
postData.put("userName", "yangfan");
String s = sendPostRequest(url, postData);
System.err.println(s);
}
public String sendPostRequest(String url, JSONObject params){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//这里设置为APPLICATION_JSON
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("loginUserId", "admin");
headers.add("loginUserOrgId", "1");
//将请求头部和参数合成一个请求
HttpEntity<JSONObject> requestEntity = new HttpEntity<>(params, headers);
//执行POST请求
ResponseEntity<String> entity = client.postForEntity(url, requestEntity, String.class);
return entity.getBody();
}
- 表单提交,远程接口使用表单方式接收参数,即不加
@RequestBody
public void saveUserWithFormData() {
//模拟远程接口
String url = "http://127.0.0.1:8080/sakura/formdata/users";
//往请求体添加参数
MultiValueMap<String, Object> postData = new LinkedMultiValueMap<>();
postData.add("userId", 123);
postData.add("username", "test");
String result = sendPostRequestWithFormData(url, postData);
//处理返回的结果
System.err.println(result );
}
public String sendPostRequestWithFormData(String url, MultiValueMap<String, Object> postData){
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//这里设置为MULTIPART_FORM_DATA
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//请求头中添加参数
headers.add("loginUserId", "admin");
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(postData, headers);
//执行POST请求
ResponseEntity<String> entity = client.postForEntity(url, requestEntity, String.class);
return entity.getBody();
}