欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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