Spring RestTemplate中几种常见的请求方式–参考链接
RestTemplate 发post请求不同的请求头,参数的封装类不一样
1,RestTemplate 的配置类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
/**
* <p>
* 配置RestTemplate,RestTemplate是Spring提供的用于访问Rest服务的客户端,提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率
* </p>
*
* @author
* @custom.date 2020年1月20日 上午10:58:31
*/
@Configuration
public class RestTemplateConfig {
private Logger log = LoggerFactory.getLogger(RestTemplateConfig.class);
/**
* <p>
* 构造RestTemplate实例,把RestTemplate实例作为一个JavaBean交给Spring管理
* </p>
*
* @return {@link RestTemplate}
*/
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplateBuilder()//
// .basicAuthorization("username", "password")
// 5秒
.setConnectTimeout(Duration.ofSeconds(5))
// 5秒
.setReadTimeout(Duration.ofSeconds(5))//
.build();
log.info("RestTemplate配置成功!");
return restTemplate;
}
}
2,restTemplate post请求及参数的封装:
public class BdeviceVms{
// springboot 自带的两个类,直接注入,无需第三方包
@Autowired
private RestTemplate restTemplate;
@Autowired
private ObjectMapper objectMapper;
//
public Map<String, Object> getVmsRealPlayListForGJ(String deviceId) {
String url = "http://ip:port/open/gateway";
String method = "query_display";
//生成唯一请求标识
String request_id = Customer.getCustomerIDincrease();
//生成鉴权码
String signValue = SignUtil.getSign(method,deviceId,request_id);
Map<String, String> mapContent = new HashMap<>();
mapContent.put("deviceCode",deviceId);
String content = null;
try {
// 将map对象转换成json 字符串
content = objectMapper.writeValueAsString(mapContent);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
// 第一种请求方式: restTemplate 模板请求post
// 1,设置请求头
HttpHeaders headers = new HttpHeaders();
//headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
// 默认请求头
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 2,封装参数,当请求头是默认的 application/x-www-form-urlencoded 时
// post请求 封装参数用MultiValueMap,千万不要用Map与HashMap,否则参数无法传递
MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<String, String>();
paramMap.add("method", method);
paramMap.add("api_request_id", request_id);
paramMap.add("sign_type", "RSA");
paramMap.add("sign", signValue);
// 而当请求头是:Content-Type 为 application/json 时,
// post请求 则要用Map与HashMap来封装参数
// Map<String, String> map = new HashMap<String, String>();
// map.put("name","hjxx");
// 3. 封装请求头和 参数
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(paramMap,headers);
//HttpEntity<Map<String, String>> httpEntity = new HttpEntity<Map<String, String>>(map,headers);
// 4,发送请求,指定请求方式
// 使用exchange请求接口
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
String res = response.getBody();
System.out.println("result3====================" + response.getBody());
// 第二种:请求方式
// Map<String, String> map = new HashMap<>();
// map.put("api_request_id", request_id);
// map.put("method", method);
// // 工具类封装了post请求 拼接参数的
// String s = DoPostUtils.doPost(url, map);
// System.out.println(s);
// 返回结果处理,将string 转成 map
Map restMap = null;
try {
restMap = objectMapper.readValue(res, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
return restMap;
}
}
3,第二种请求方式:用的工具类(与restTemplate 无关);
pom.xml
<dependency>
<groupId>com.arronlong</groupId>
<artifactId>httpclientutil</artifactId>
<version>1.0.4</version>
</dependency>
工具类
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author
* @create 2020-08-26 9:10
* 将参数拼接在请求地址后面发送post请求
* 发送示例:
* http://IP:port/baidu.com?action=2&yydm=kfcs&paytype=3¬ifyUrl=1&czyh=wnpay&outSignNo=1 //post请求
*/
public class DoPostUtils {
/**
*
* @param url
* @param param
* @return String
* post请求示例 http://IP:port/baidu.com?action=2&yydm=kfcs&paytype=3¬ifyUrl=1&czyh=wnpay&outSignNo=1
*/
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
//System.out.println( resultString);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
}