天天看点

【web】Spring RestTemplate提交时设置http header请求头

在web开发时进程遇到需要编写一些小的测试用例用于测试api接口是否可用,此时使用Spring框架的开发者大多会想到使用RestTemplate。本文实现一个使用RestTemplate发起GET请求,同事设置GET请求的http头的示例。

1、创建测试类的基类

创建一个测试类的基类BaseTester,用于导入测试类的配置文件,本例中配置文件使用的时java注解的config类。基类代码如下:

package api.landsem.tester.ram;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { EmptyConfiguration.class })
public class BaseTester {

}
           

2、创建配置类

上面创建的测试基类中导入了一个名为EmptyConfiguration的配置类,该配置类的代码如下:

package api.landsem.tester.ram;

import org.springframework.context.annotation.Configuration;

@Configuration
public class EmptyConfiguration {

}
           

3、创建测试代码

如下为一个简单的测试代码,该代码实现从一个指定的api接口请求数据,在请求时设置http请求的头信息,源码如下:

package api.landsem.tester.ram.api;

import java.util.Date;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import api.landsem.ram.factory.SignatureHelper;
import api.landsem.tester.ram.BaseTester;
import api.landsem.utils.LocalDateUtils;
import api.landsem.utils.TokenUtils;

public class CertificateCheckApiTester extends BaseTester{
	private final static Logger logger = Logger.getLogger(CertificateCheckApiTester.class);
	
	private final static String testKey = "LSadsfdslfm";
	private final static String testSecret = "LSerkfdksvdsf";
	private final static int intent = 101;
	private final static String code = "2asfd5f69699532325686";
	private final static String number = "665533255555";
	private final static String salt = "10";	  
	
	@Test
	public void test() {
	   logger.info("call test.");
	   final String url = "http://192.168.1.245:8082/ram/ram/v1/certificates";
	   HttpHeaders requestHeaders = new HttpHeaders();
           requestHeaders.add("key", testKey);
           requestHeaders.add("intent", String.valueOf(intent));
           requestHeaders.add("number", number);
           requestHeaders.add("code", code);
	   RestTemplate template = new RestTemplate();
	   HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
           ResponseEntity<String> response = template.exchange(url, HttpMethod.GET, requestEntity, String.class);
           String sttr = response.getBody();
           logger.info("sttr="+sttr);
	}

}