restTemplate请求发送模板

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class HttpService {

    @Resource
    private RestTemplate restTemplate;

    public HttpEntity<Map<String, String>> generatePostJson(Map<String, String> jsonMap) {
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        return new HttpEntity<>(jsonMap, httpHeaders);
    }

    public String sendJsonPost(String uri, Map<String, String> jsonMap) {
        ResponseEntity<String> apiResponse = restTemplate.postForEntity(uri, generatePostJson(jsonMap), String.class);
        return apiResponse.getBody();
    }

    public String sendPost(String uri, String param) {
        ResponseEntity<String> apiResponse = restTemplate.postForEntity(uri, param, String.class);
        return apiResponse.getBody();
    }
}

  

posted @ 2022-03-28 08:44  小小菜包子  阅读(26)  评论(0)    收藏  举报