RestTemplate 请求参数格式JSON

我们一般在项目中会遇到某个需求和上一个项目的需求一模一样,那我们就会直接去访问之前项目的接口,不会在另写,或者说调用3方接口。这就用到RestTemplate ,RestTemplate简单的理解就是:简化了发起 HTTP 请求以及处理响应的过程。

自己在本地搭建了两个项目,通过B项目去访问A项目中的接口并处理返回数据;还是老样子,直接看代码。

我首先搭建了两个项目分别是spring-boot和spring-boot-restTemplate;我把spring-boot项目看作三方服务,

然后我在spring-boot项目里面写了一个测试接口来供spring-boot-restTemplate项目调用;因为我们说了是做json的格式传递参数嘛,所以我用了@requestBody,请看下面的代码

package com.steven.controller.appController.test;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import com.steven.entity.User;
import com.steven.entityVo.param.Param;
import com.steven.service.UserService;
import com.steven.utils.json.Json;
import com.steven.utils.result.Result;
 
@Controller
@RequestMapping(value="/test")
public class Test {
 
    @Autowired
    private UserService userService;
    /**
     * 查询用户详细信息
     * @param response
     * @param userId
     */
    @RequestMapping(value="/findOne", method=RequestMethod.POST)
    public void findOne(HttpServletRequest request, HttpServletResponse response, @RequestBody Param param) throws Exception{
 
        Integer userId = param.getUserId();
        User user = userService.findOne(userId);
        if(user == null){
            Json.toJson(new Result(false,1,"该用户不存在",null), response);
            return;
        }
        Json.toJson(new Result(true, 0, "获取用户信息成功", user), response);
    }
}
接下来就是重点了,主要讲RestTemplate了,在我们项目中引用RestTemplate 需要注册RestTemplate Bean 也就是说我们要写一个配置文件来配置它。这个也很简单,网上资料一大堆。

package com.steven.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
 
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(10000);//单位为ms
        factory.setConnectTimeout(10000);//单位为ms
        return factory;
    }
}
再然后就是我们的测试接口了,下面代码主要重点关注一下HttpEntuty对象,它其实就是传参的重点。

package com.steven.controller.appController.test;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
 
import com.alibaba.fastjson.JSONObject;
import com.steven.entity.User;
import com.steven.utils.json.Json;
import com.steven.utils.result.Result;
import com.steven.utils.string.StringUtil;
 
@Controller
@RequestMapping(value="/test")
public class Test {
    //调用spring里面RestTemplate需要配置bean
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * post请求远程调用
     * @param response
     * @param userId
     * @throws Exception
     */
    @RequestMapping(value="/doPost", method=RequestMethod.POST)
    public void  doPost(HttpServletResponse response, Integer userId) throws Exception{
        String url="http://127.0.0.1/test/findOne";
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        //RestTemplate带参传的时候要用HttpEntity<?>对象传递
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(map, headers);
        
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        //获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串;
        String body = entity.getBody();
        //然后把str转换成JSON再通过getJSONObject()方法获取到里面的result对象,因为我想要的数据都在result里面
        //下面的strToJson只是一个str转JSON的一个共用方法;
        JSONObject json = StringUtil.strToJson(body);
        if(json != null){
            JSONObject user_json = json.getJSONObject("result");
            //这里考虑 到result也可能为null的情况,因为字符串转json会把字段为null的过滤掉;
            if(user_json != null && !"{}".equals(user_json.toString())){
                //调用JSONObject.toJavaObject()把JSON转成java对象最后抛出数据即可
                User user = JSONObject.toJavaObject(user_json, User.class);
                //最后抛出json数据
                Json.toJson(new Result(true, 0, "获取信息成功", user), response);
                return;
            }else{
                Json.toJson(new Result(false, 1, "没有信息", null), response);
                return;
            }
        }else{
            Json.toJson(new Result(false, 1, "没有信息", null), response);
        }
    }
    
}
最后看下测试结果测试成功。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值