RestTemplate 请求参数格式JSON

标签: RestTemplate

我们一般在项目中会遇到某个需求和上一个项目的需求一模一样,那我们就会直接去访问之前项目的接口,不会在另写,或者说调用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);
		}
	}
	
}

最后看下测试结果测试成功。



版权声明:本文为sex_man原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sex_man/article/details/79783613

智能推荐

RestTemplate的请求参数传递问题 RestTemplate发送Get请求通过body传参问题

RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能,但只有理解了HttpEntity的组成结构(header与body),且理解了与uriVariables之间的差异,才能真正掌握其用法。 此文章主要写了 Get 和 Post请求的 ForObject ,ForEntity 和exchange这三种方式的提交数据 话不多说 直接上代码 在启动文件中 配置r...

SpringBoot RestTemplate 请求工具类

SpringBoot RestTemplate 请求工具类 Naotu 请求日志拦截器 创建 单例 RestTemplate 工具类 测试 测试日志 Naotu 请求日志拦截器 创建 单例 RestTemplate 工具类 测试 测试日志...

RestTemplate发送HTTP、HTTPS请求

        前面我们介绍了如何使用Apache的HttpClient发送HTTP请求,这里我们介绍Spring的Rest客户端(即:RestTemplate) 如何发送HTTP、HTTPS请求。注:HttpClient如何发送HTTPS请求,有机会的话也会再给出示例。 声明:本人一些内容摘录自其他朋友的博客,链接在本文末给出!   基础知识 &...

使用RestTemplate发起Http请求

这里主要记录一下get请求和post请求的使用。 首先,看一下啊RestTemplate的源码方法: 可以看到两种请求得方法大同小异。XXForEntity返回的是ResponseEntity类型的数据,其中包含了头信息和返回内容。而XXForObject返回的是约定好的一个类型,其中只有返回的内容信息。 postForLocation返回了一个URI对象,这个指的是新资源的地址。 下面来看看具体...

Url请求 -- Spring RestTemplate 专题

Spring RestTemplate 专题 相同的参数(接口的入参json打印在日志了)在PostMan中返回预期的数据,但使用RestTemplate时去提示信息错误(参数中汉字)。 这种情况,搞得怀疑对RestTemplate的理解了 使用RestTemplate的代码如下:   解决办法,通过wireshark抓包: 使用Postman发送时情况: 使用上面的代码调接口时的htt...

猜你喜欢

NTP服务器搭建(运维实用小项目)

环境介绍 两台centos7 192.168.59.130 192.168.59.131 server端192.168.59.131安装NTP服务 修改配置文件 重启ntp服务 客户机192.168.59.130安装ntpdate...

RecycleView Grid样式的分割线,均分每行

说明 最近写一个GridView的布局,需要一个较宽的分割线样式,发现自己以前写的还有网上的很多都有问题,主要存在没考虑到divider也有一定宽度,这样导致第一行特别宽,其他行都较短。 特修改bug,顺便分享一下 原理 其实很简单,主要就是在 重新 ItemDecoration 的 getItemOffsets方法 给设置每块的布局添加偏移量padding,注释都在里面 totalwidth =...

C语言实现通讯录

一、通讯录要求: 实现一个通讯录; 通讯录可以用来存储1000个人的信息,每个人的信息包括:姓名、性别、年龄、电话、住址 提供方法: 添加联系人信息 删除指定联系人信息 查找指定联系人信息 修改指定联系人信息 显示所有联系人信息 清空所有联系人 以名字排序所有联系人 二、代码实现 1.头文件和宏定义 2.定义联系人结构体和通讯录结构体 3.定义一个结构体指针类型Func 定义一个AddressBo...

Hive分区

创建分区表  dt 是分区列 增加分区 删除分区 导入分区数据 准备数据 pt1-2018-07-13.txt 和 pt1-2018-07-14.txt 导入数据 查看hdfs hdfs查询分区 hdfs显示分区信息 本机环境hadoop-2.7.6目录不支持=号,查询时用?代替 hive查询分区数据...

外部类,内部类以及静态内部类的加载关系深入探讨

前言:   在看单例模式的时候,在网上找帖子看见其中有一种(IoDH) 实现单例的方式,其中用到了静态内部类,文章中有写到当jvm加载外部类的时候,并没有加载静态内部内这和之前自己想的不一样,特意在网上找了一些帖子总结一下。 一、学习前千的疑问:   稍微了解Java虚拟机内的加载过程的步骤,都很清楚,一个类的静态资源、一些常量都是在类加载的时候就被加载金内存中分配空间了,所以我一开始理所当然的以...