赞
踩
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_id=").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提交和表单提交两种示例
@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(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。