【web】Spring RestTemplate提交時設定POST請求引數

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請求,並設定post請求的引數,程式碼如下:

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.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
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 CertificateRegistApiTester extends BaseTester{
	private final static Logger logger = Logger.getLogger(CertificateRegistApiTester.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";
		RestTemplate template = new RestTemplate();		
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
				

		MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
		map.add("key", testKey);
		map.add("intent", String.valueOf(intent));
		map.add("number", number);
		map.add("code", code);
		map.add("signature", signature);
		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,null);
		ResponseEntity<String> response = template.postForEntity( url, request , String.class );		
		logger.info("response="+response.getBody());
	}

}


相關文章