resttemplate

@Autowired
private RestTemplate restTemplate

String url="https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=3ff9482454cb60bcb73f65c8c48d4209](https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=3ff9482454cb60bcb73f65c8c48d4209)";
//无参 不用指定header的请求
JSONObect jsonobject=restTemplate.getForObject(url,JSONObject.class);

//无参指定header的请求
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "application/json");
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>( headers);
JSONObject jsonobject=restTemplate.getForObject(url,JSONObject.class,httpEntity);

//有参,param方式的参数【参数是拼接在url路径上】
Map<String, Object> params = new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
JSONObject jsonobject=restTemplate.getForObject(url,JSONObject.class,params);

//有参,请求体body中json【较少见,调用方式如下:】
因为restTemplate默认使用的jdk的requestfactory,这种方式不支持get请求这样的传参,故需要将restTemplate的requestfactory设置为自定义的requestfactory继承HttpEntityEnclosingRequestBase具体如下:
private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
        @Override
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (httpMethod == HttpMethod.GET) {
                return new HttpGetRequestWithEntity(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    }
    private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
        public HttpGetRequestWithEntity(final URI uri) {
            super.setURI(uri);
        }

        @Override
        public String getMethod() {
            return HttpMethod.GET.name();
        }
    }
此种方式下的调用
        String temp="";//参数的json串
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity<JSONObject> httpEntity = new HttpEntity(temp, headers);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());//或者在注入之前set该requestfactory
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        String body = exchange.getBody();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值