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

RestTemplate发送post请求服务

程序员文章站 2022-06-24 23:50:49
...

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

}

相关标签: json post