java中利用spring 提供的 RestTemplate发送http请求

1.搭建Spring框架

2.在使用类中直接注入

@Autowired
private RestTemplate restTemplate;

3.向指定url发送无请求头消息验证的get请求

/**
 * 〈〉根据url 发送求情获取json结果
 *
 * @Date: 2018/8/1 19:37
 */
public String getJson(String url){
    String result = null;
    try{
        result =  restTemplate.getForObject(url,String.class);
    }catch(Exception e){
        logger.error("请求" + url + "请求失败");
        logger.error(e.getMessage(),e);
    }
    return result;
}

4.发送含有token信息校检的请求

public String getJson(String url){
    String result = null;
    try{
        HttpHeaders headers = new HttpHeaders(); 
       //设置服务端接收方式为json
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());                       
        headers.setContentType(MediaType.APPLICATION_JSON); 
       //请求头中添加token等验证信息
        headers.add("Cookie", "uuid=ef18beae-9fc9-47df-a92b-    d2df242e9fc7;shop_id=13299275;wxrrd_mch_session=eyJpdiI6InhYRFdaczliZ2VBbFhBZEZ4bThBSXc9PSIsInZhbHVlIjoicmdhUG1nZlZWeDNCSFhDUVA4MHdIenQrUXY4MXhDS1hrUjF4Mk5TZlJlRG9iQ1hHczBzSjVpaGNIZjFLWWJxUkdwWFUrTnpDMW1Fa0VzSFBTV3RLbFE9PSIsIm1hYyI6ImIwYmRjNTVjOTJmMWM2YzhkM2EzYWIzNTcwMTcwMjJmNTg2MDRmOTc4N2UzYTU2NjEzYzZmNDI0YzI3NDgyNTcifQ%3D%3D");
        HttpEntity httpEntity = new HttpEntity("Client", headers); 
        ResponseEntity responseEntity = this.restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class, new Object[0]); 
    String result = (String)responseEntity.getBody();
    }catch(Exception e){
        logger.error("请求" + url + "请求失败");
        logger.error(e.getMessage(),e);
    }
    return result;
}
 

 

你可能感兴趣的:(http请求,RestTemplate,http请求,Spring)