restTemplate 发送 form body
程序员文章站
2022-06-24 22:25:32
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
添加依赖
package com.example.provider.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class HttpClientUtil {
private static final Logger logger= LoggerFactory.getLogger(HttpClientUtil.class);
public static String formPost(String url, MultiValueMap<String,String> map){
logger.info("url={},map={}",url,map);
RestTemplate restTemplate=new RestTemplate();
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String,String>> request=new HttpEntity<MultiValueMap<String,String>>(map,headers);
ResponseEntity<String> response=restTemplate.postForEntity(url,request,String.class);
return response.getBody();
}
public static String jsonPost(String url,String bodyJson){
RestTemplate restTemplate=new RestTemplate();
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
headers.add("Accept",MediaType.APPLICATION_JSON.toString());
HttpEntity<String> httpEntity=new HttpEntity<String>(bodyJson,headers);
ResponseEntity<String> response=restTemplate.postForEntity(url,httpEntity,String.class);
return response.getBody();
}
}
推荐阅读
-
java map转Multipart/form-data类型body实例
-
java模拟发送form-data的请求方式
-
RestTemplate发送带请求头的Json的Post请求Utils工具类
-
RestTemplate的请求参数传递问题 RestTemplate发送Get请求通过body传参问题
-
RestTemplate实现发送带headers的GET请求
-
axios发送post form请求
-
我遇到过的坑-Spring 使用form发送put,delete请求
-
Spring使用RestTemplate模拟form提交示例
-
restTemplate 发送 MultiValueMap 中文乱码 (FormHttpMessageConverter 编码方式)
-
使用spring 中的RestTemplate 发送请求 实现httpclient