RestTemplate发送post请求服务

    技术2022-07-27  76

    package com.test.bank.util;

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate;

    @Service public class HttpRequestUtil {

    @Autowired private RestTemplate restTemplate; public String post(String url, String json) { return post(url, json, "application/json; charset=UTF-8", restTemplate); } public String post(String url, String json, String type, RestTemplate restTemplate) { HttpHeaders headers = new HttpHeaders(); MediaType mediaType = MediaType.parseMediaType(type); headers.setContentType(mediaType); HttpEntity<String> requestEntity = new HttpEntity<>(json, headers); String result = restTemplate.postForObject(url, requestEntity, String.class); return result; } public String get(String url) { return restTemplate.getForObject(url, String.class); }

    }

    Processed: 0.009, SQL: 9