RestTemplate包装请求参数,请求接口并获取返回值

//创建restTemplate和HttpHeaders头部对象
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//设置请求方式
HttpMethod method = HttpMethod.POST;
//设置提交方式为表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//实例化请求参数对象,并添加请求参数
LinkedMultiValueMap body = new LinkedMultiValueMap();
body.add("key1","val1");
body.add("key2","val2");
body.add("key3","val3");
//将请求头部和参数合成一个请求
HttpEntity requestEntity = new HttpEntity(body,headers);
//执行HTTP请求,将返回的结构格式化
ResponseEntity<String> exchange = client.exchange(WATCH_SIGN_URL, method, requestEntity, String.class);
//通过FastJson解析返回参数
JSONObject jsonObject = JSONObject.parseObject(exchange.getBody());
jsonObject.get("data1");
jsonObject.get("data2");

你可能感兴趣的:(java)