RestTemplate 访问API Gson

private static final RestTemplate REST_CLIENT = new RestTemplate();
<pre style="font-family: 'Source Code Pro'; font-size: 10.5pt; background-color: rgb(255, 255, 255);">String volumeStr = <span style="color:#660e7a;"><strong><em>REST_CLIENT</em></strong></span>.getForObject(<span style="color:#008000;"><strong>url</strong></span>, String.<span style="color:#000080;"><strong>class</strong></span>);
//getForObject API类型为get post:postForObject
<p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15px; line-height: 35px; background-color: rgb(255, 255, 255);">RestTemplate的getForObject完成get请求、postForObject完成post请求、put对应的完成put请求、delete完成delete请求;还有execute可以执行任何请求的方法,需要你设置RequestMethod来指定当前请求类型。</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15px; line-height: 35px; background-color: rgb(255, 255, 255);">RestTemplate.getForObject(String url, Class responseType, String... urlVariables)</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15px; line-height: 35px; background-color: rgb(255, 255, 255);">参数url是http请求的地址,参数Class是请求响应返回后的数据的类型,最后一个参数是请求中需要设置的参数。</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15px; line-height: 35px; background-color: rgb(255, 255, 255);">template.getForObject(url + "get/{id}.do", String.class, id);</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15px; line-height: 35px; background-color: rgb(255, 255, 255);">//第二种访问API</p><p style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px; color: rgb(85, 85, 85); font-family: 'microsoft yahei'; font-size: 15px; line-height: 35px;"><pre style="font-family: 'Source Code Pro'; font-size: 10.5pt;"><span style="background-color: rgb(255, 255, 255);">String content = Request.<span style="font-style:italic;">Get</span>(</span><span style="background-color: rgb(228, 228, 255);">url</span><span style="background-color: rgb(255, 255, 255);">) .execute().returnContent().asString();</span>
//请求导的json字符串转换成List<String>
Gson gson = new Gson();
List<String>= gson.fromJson(content, new TypeToken<List<String>>() {
}.getType());


 


 
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值