【web】Spring RestTemplate提交時設定http header請求頭

yingxian_Fei發表於2018-01-08

在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);
	}

}




相關文章