java使用RestTemplate访问接口


前言

上一章介绍了java使用httpclient访问接口,接下来spring的RestTemplate模拟http请求,代码更加简洁、使用范围更加广泛,尤其在springcloud使用更加如鱼得水,在springcloud中使用RestTemplate可以很容易地访问注册中心里其他系统的接口服务。


一、引入依赖

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>5.0.4.RELEASE</version>
 </dependency>

二、代码部分

1.服务方

代码如下(示例):

package com.student.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.Random;

/**
 * Create by zjg on 2023/4/27
 */
@RequestMapping("/http/")
@RestController
public class HttpClientController {
    @GetMapping("client")
    public JSONObject get(String province, String city, String area){
        return getWeather(province,city,area,"GET");
    }
    @PostMapping("client")
    public JSONObject post(@RequestBody JSONObject jsonObject){
        return getWeather(jsonObject.getString("province"),jsonObject.getString("city"),jsonObject.getString("area"),"POST");
    }
    public JSONObject getWeather(String province,String city,String area,String type){
        String []weathers={"晴","多云","小雨","中雨","大雨","暴雨"};
        int index= new Random().nextInt(weathers.length);
        JSONObject jsonObject = new JSONObject();
        LocalDate now = LocalDate.now();
        jsonObject.put("weather",province+city+area+" "+now+":"+weathers[index]);
        jsonObject.put("type",type);
        return jsonObject;
    }
}

2.请求方

代码如下(示例):

package test;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Iterator;
import java.util.Map;

/**
 * Create by zjg on 2023/7/21
 */
public class RestTemplateTest {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url="http://127.0.0.1:8080/http/client";;
        MultiValueMap<String,String> headers = new HttpHeaders();
        JSONObject body = new JSONObject();
        body.put("province","山东省");
        body.put("city","济南市");
        body.put("area","历城区");
        HttpEntity<JSONObject> entity = new HttpEntity<>(body, headers);
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, entity, JSONObject.class);
        System.out.println(responseEntity.getStatusCode());
        System.out.println(responseEntity.getBody());
        url+="?";
        Iterator<Map.Entry<String, Object>> iterator = body.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            url+=entry.getKey()+"="+entry.getValue()+"&";
        }
        ResponseEntity<JSONObject> responseEntity1 = restTemplate.getForEntity(url.substring(0,url.length()-1), JSONObject.class);
        System.out.println(responseEntity1.getStatusCode());
        System.out.println(responseEntity1.getBody());
    }
}

三、执行结果

200
{“weather”:“山东省济南市历城区 2023-07-21:多云”,“type”:“POST”}
200
{“weather”:“山东省济南市历城区 2023-07-21:暴雨”,“type”:“GET”}


总结

回到顶部
关于在springcloud中的使用,后续有机会会更新。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RestTemplate 是 Spring Framework 提供的一个用于访问 RESTful 服务的模板类。它可以用来发送 HTTP 请求,并处理响应数据。 要使用 RestTemplate 调用 HTTP 接口,您需要做以下步骤: 1. 导入依赖:在项目的构建文件中(如 Maven 或 Gradle)添加 RestTemplate 的依赖。 2. 创建 RestTemplate 实例:在您的代码中,使用 `new RestTemplate()` 创建一个 RestTemplate 实例。 3. 发送 HTTP 请求:使用 RestTemplate 实例的 `getForObject()`、`postForObject()` 等方法发送 HTTP 请求。例如,要发送一个 GET 请求,可以使用 `getForObject(url, responseType)` 方法,其中 `url` 是接口的 URL 地址,`responseType` 是期望的响应数据类型。 示例代码如下: ```java import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class MyClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/resource"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); String responseBody = response.getBody(); System.out.println(responseBody); } } ``` 上述示例代码中,我们创建了一个 RestTemplate 实例,并使用 `getForEntity()` 方法发送了一个 GET 请求。`response.getBody()` 方法用于获取响应的主体内容。 当然,您也可以使用其他 HTTP 方法(如 POST、PUT、DELETE 等),根据具体接口的需求来选择合适的方法。 希望以上信息对您有帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值