public class HttpRequestUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
public static String sendWithSpringRest(String url,String json,HttpMethod httpMethod) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application","json",Charset.forName("UTF-8")));
headers.setAccept(Arrays.asList(new MediaType[] {new MediaType("application","json",Charset.forName("UTF-8"))}));
HttpEntity<String> requestEntity = new HttpEntity<String>(json,headers);
ResponseEntity<String> exchange = restTemplate.exchange(url, httpMethod,requestEntity,String.class);
String body = exchange.getBody();
logger.info("-------------->"+body);
return body;
}
}
@Autowired
private RestTemplate restTemplate;
@GetMapping("/forObject")
public Map<String, Object> testForObject(Map<String, Object> params){
Map<String, Object> retMap = new HashMap<String, Object>();
Map<String, Object> paramsRest = new HashMap<String, Object>();
paramsRest.put("userName", "用戶名");
paramsRest.put("userPwd", "123456");
String urlTemplate = "http://localhost:8888/rest"+"?userName={userName}&userPwd={userPwd}";
Map forObject = this.restTemplate.getForObject(urlTemplate,Map.class,paramsRest);
System.out.println("--------result------------->"+forObject);
return retMap;
}
@RequestMapping("/exchange")
public Map<String, Object> testExchange(){
String url = "http://localhost:8888/rest";
HttpHeaders headers = new HttpHeaders();
// 請勿輕易改變此提交方式,大部分的情況下,提交方式都是表單提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封裝參數,千萬不要替換爲Map與HashMap,否則參數無法傳遞
MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
// 也支持中文
params.add("userName", "用戶名");
params.add("userPwd", "123456");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
// 執行HTTP請求
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
// 輸出結果
System.out.println("-----------responseBody------------>"+response.getBody());
return null;
}