RestTemplate模板对象封装HttpClient 对PRC的实现

1. RestTemplate模板对象介绍

1.1创建spring-resttmplate(jar)项目

1.2添加依赖

1.3  application-server.xml

1.4 测试restTemplate对象发送post请求

1.5使用RestTemplate对象发送Get请求

1.6 使用RestTemplate对象发送Post请求

代码总结:



1. RestTemplate模板对象介绍

Spring提供的用来发送http请求的对象,完成httpclient操作的封装

1.1创建spring-resttmplate(jar)项目

1.2添加依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bjsxt.rest</groupId>
  <artifactId>spring-resttemplate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  	<!-- spring依赖 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.3.18.RELEASE</version>
	</dependency>
	<!-- 添加jackson依赖 -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.9.3</version>
		</dependency>
  </dependencies>
</project>

1.3  application-server.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"      
	xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"              
    xsi:schemaLocation="                                               
            http://www.springframework.org/schema/beans    
            http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/context    
            http://www.springframework.org/schema/context/spring-context.xsd   
          ">
   	<!-- 实例化RestTemplate对象 -->
   	<bean id="template" class="org.springframework.web.client.RestTemplate"></bean>
     
     
     
</beans>

1.4 测试restTemplate对象发送post请求

package com.bjsxt.app;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.bjsxt.pojo.Orders;

public class RestTemplateApp {

	static RestTemplate template;
	/***
	 * 测试RestTemplate对象的使用
	 */
	public static void main(String[] args) {
		//加载Spring容器
		ApplicationContext ac
			=new ClassPathXmlApplicationContext("application-service.xml");
		//获得容器中的RestTemplate对象
		template = (RestTemplate) ac.getBean("template");
		
		sendPost();
	}
	
	/***
	 * 是RestTemplate对象发送Post
	 */
	public static void sendPost() {
		
		//创建LinkedMultiValueMap封装请求头信息
		LinkedMultiValueMap<String,String> 
			headers=new LinkedMultiValueMap<String,String>();
		headers.add("Content-Type", "application/x-www-form-urlencoded");
		
		//封装请求体数据
		LinkedMultiValueMap<String,String> body=
				new LinkedMultiValueMap<String,String>();
		body.add("vid", "12345678");
		
		
		//创建HttpEntity对象,封装请求体和请求头信息
		HttpEntity<LinkedMultiValueMap<String,String>> 
			entity=new HttpEntity<>(body,headers);
		
		String url="http://localhost:8081/loadOrdersList";
		//发送http,post请求,获得请求体
		//Orders[] results=template.postForObject(url,entity, Orders[].class);
		//List<Orders> asList = Arrays.asList(results);
		
		//发送http,post请求,响应回来请求头和请求体
		ResponseEntity<Orders[]> response 
			= template.postForEntity(url,entity, Orders[].class);
		//获得请求头
		int statusCodeValue = response.getStatusCodeValue();
		System.out.println(statusCodeValue);
		//获得请求体
		Orders[] results = response.getBody();
		for(Orders orders:results) {
			System.out.println(orders.getId()+"\t"+orders.getRemark()
			+"\t"+orders.getOdate()+"\t"+orders.getVip());
		}
	}
	/***
	 * 是RestTemplate对象发送Get
	 */
	/***
	 * 是RestTemplate发送Post请求,提交json字符串
	 */
	
	
}

1.5使用RestTemplate对象发送Get请求

/***
	 * 是RestTemplate对象发送Get
	 */
	public static void sendGet() {
		String url="http://localhost:8081/loadOrders?id=888888";
		/***
		 * ResponseEntity 封装了请求头和请求体
		 */
		//ResponseEntity<Orders> entity = template.getForEntity(url, Orders.class);
		//Orders orders = entity.getBody();
		
		//只获得请求体
		Orders orders = template.getForObject(url, Orders.class);
		System.out.println(orders.getId()+"\t"+orders.getRemark()
			+"\t"+orders.getVip()+"\t"+orders.getOdate());
		
	}

1.6 使用RestTemplate对象发送Post请求

/***
	 * 是RestTemplate发送Post请求,提交json字符串
	 */
	public static void sendPostObject() {
		//创建Orders对象
		Orders orders=new Orders();
		orders.setId(77777777);
		orders.setRemark("周末配送....");
		orders.setOdate("2010-10-10");
		orders.setVip(99999);
		
		//封装请求头信息
		HttpHeaders header=new HttpHeaders();
		header.setContentType(MediaType.APPLICATION_JSON_UTF8);
		
		//将javabean对象转化为json字符串
		String jsonString = JSON.toJSONString(orders);
		//将请求体和请求头信息封装
		HttpEntity<String> entity=new HttpEntity<String>(jsonString,header);
		
		String url="http://localhost:8081/saveOrders";
		//发送post请求
		Map result = template.postForObject(url, entity, Map.class);
		System.out.println(result);
		
	}

 

代码总结:

import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.bjsxt.pojo.Orders;
import com.fasterxml.jackson.databind.util.JSONPObject;

public class RestTemplateTest {
	static RestTemplate template;

	public static void main(String[] args) {
		// 加载Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("application-service.xml");
		// 获得容器中的RestTemplate对象
		template = (RestTemplate) ac.getBean("template");

		sendObject();
	}

	// 发送post请求
	public static void sendPost() {
		// 创建LinkedMultiValueMap封装请求头信息
		LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
		headers.add("Content-Type", "application/x-www-form-urlencoded");

		// 封装请求体数据
		LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
		body.add("vid", "12345678");

		// 创建HttpEntity对象,封装请求体和请求头信息
		HttpEntity<LinkedMultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);

		String url = "http://localhost:8081/loadOrdersList";
		// 发送http,post请求,获得请求体
		// Orders[] results=template.postForObject(url,entity, Orders[].class);
		// List<Orders> asList = Arrays.asList(results);

		// 发送http,post请求,响应回来请求头和请求体
		ResponseEntity<Orders[]> response = template.postForEntity(url, entity, Orders[].class);
		// 获得请求头
		int statusCodeValue = response.getStatusCodeValue();
		System.out.println(statusCodeValue);
		// 获得请求体
		Orders[] results = response.getBody();
		for (Orders orders : results) {
			System.out.println(
					orders.getId() + "\t" + orders.getRemark() + "\t" + orders.getOdate() + "\t" + orders.getVip());
		}
	}

	// 发送get请求
	public static void sendGet() {
		String url = "http://localhost:8081/selectOrder?id=88888";
		ResponseEntity<Orders> response = template.getForEntity(url, Orders.class);
		Orders body = response.getBody();
		System.out.println(body);
	}

	// 发送对象json字符串
	public static void sendObject() {
		// 创建Orders对象
		Orders orders = new Orders();
		orders.setId(77777777);
		orders.setRemark("周末配送....");
		orders.setOdate("2010-10-10");
		orders.setVip(99999);
		String url="http://localhost:8081/addOrders";
		//把对象封装为json字符串
		String jsonString = JSON.toJSONString(orders);
		//封装响应头为json'格式的响应
		HttpHeaders header=new HttpHeaders();
		header.setContentType(MediaType.APPLICATION_JSON_UTF8);
		//传入两个对象(第一个是请求体、第二个是请求头)
		HttpEntity<String>request=new HttpEntity<>(jsonString,header);
		Map<String, String>map
			= template.postForObject(url, request, Map.class);
		System.out.println(map);
		
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值