springboot发送post请求封装工具类
时间: 2023-09-25 21:09:18 浏览: 51
以下是一个简单的封装工具类,用于发送POST请求:
```
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;
import java.util.Map;
public class HttpUtil {
private static RestTemplate restTemplate = new RestTemplate();
public static ResponseEntity<String> post(String url, Map<String, String> params) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
map.add(entry.getKey(), entry.getValue());
}
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
return restTemplate.postForEntity(url, request, String.class);
}
}
```
使用方法:
```
Map<String, String> params = new HashMap<>();
params.put("name", "John");
params.put("age", "25");
ResponseEntity<String> response = HttpUtil.post("http://example.com/api/user", params);
String result = response.getBody();
```