java使用RestTemplate访问接口

文章目录

  • 前言
  • 一、引入依赖
  • 二、代码部分
    • 1.服务方
    • 2.请求方
  • 三、执行结果
  • 总结


前言

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


一、引入依赖

<dependency>
   <groupId>org.springframeworkgroupId>
   <artifactId>spring-webartifactId>
   <version>5.0.4.RELEASEversion>
 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中的使用,后续有机会会更新。

你可能感兴趣的:(java,java,开发语言)