RestTemplate发送http协议和https协议的get,post请求

工具类

直接调用就行,封装好的

public class HttpUtil {
    /**
     * 通过http协议发送post
     * @param url
     * @param param
     */
    public static String sendPostHttp(String url, Map<String, Object> param){
        RestTemplate restTemplate = new RestTemplate();
        //编码为utf-8
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(param, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        //获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串;
        return entity.getBody();
    }
    /**
     * 通过http协议发送get
     * @param url
     * @param param
     */
    public static String sendGetHttp(String url, Map<String, Object> param){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //处理参数
        StringBuilder builder = new StringBuilder();
        if (param != null) {
            for (String key : param.keySet()) {
                builder.append(key + "=" + param.get(key) + "&");
            }
        }
        ResponseEntity<String> res = restTemplate.getForEntity(url+"?"+builder, String.class);
        return res.getBody();
    }


    /**
     * 使用https协议发送post
     * @param url 请求地址
     * @param param 参数
     */
    public static String sendPostHttps(String url, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        //编码为utf-8
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(param, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        //获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串;
        return entity.getBody();
    }

    /**
     * 使用https协议发送get
     * @param url 请求地址
     * @param param 参数
     */
      public static String sendGetHttps(String url, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        //编码为utf-8
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //处理参数
        StringBuilder builder = new StringBuilder();
        if (param != null) {
            for (String key : param.keySet()) {
                builder.append(key + "=" + param.get(key) + "&");
            }
        }
        ResponseEntity<String> res = restTemplate.getForEntity(url+"?"+builder, String.class);
        return res.getBody();
    }

}

https协议的工具类

public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
    private static final int DEFAULT_CHUNK_SIZE = 4096;
    private Proxy proxy;
    private boolean bufferRequestBody = true;
    private int chunkSize = 4096;
    private int connectTimeout = -1;
    private int readTimeout = -1;
    private boolean outputStreaming = true;
    private AsyncListenableTaskExecutor taskExecutor;

    public SimpleClientHttpRequestFactory() {
    }

    public void setProxy(Proxy proxy) {
        this.proxy = proxy;
    }

    public void setBufferRequestBody(boolean bufferRequestBody) {
        this.bufferRequestBody = bufferRequestBody;
    }

    public void setChunkSize(int chunkSize) {
        this.chunkSize = chunkSize;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public void setOutputStreaming(boolean outputStreaming) {
        this.outputStreaming = outputStreaming;
    }

    public void setTaskExecutor(AsyncListenableTaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
        HttpURLConnection connection = this.openConnection(uri.toURL(), this.proxy);
        this.prepareConnection(connection, httpMethod.name());
        return (ClientHttpRequest)(this.bufferRequestBody ? new SimpleBufferingClientHttpRequest(connection, this.outputStreaming) : new SimpleStreamingClientHttpRequest(connection, this.chunkSize, this.outputStreaming));
    }

    public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
        Assert.state(this.taskExecutor != null, "Asynchronous execution requires an AsyncTaskExecutor to be set");
        HttpURLConnection connection = this.openConnection(uri.toURL(), this.proxy);
        this.prepareConnection(connection, httpMethod.name());
        return (AsyncClientHttpRequest)(this.bufferRequestBody ? new SimpleBufferingAsyncClientHttpRequest(connection, this.outputStreaming, this.taskExecutor) : new SimpleStreamingAsyncClientHttpRequest(connection, this.chunkSize, this.outputStreaming, this.taskExecutor));
    }

    protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
        URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
        Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
        return (HttpURLConnection)urlConnection;
    }

    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        if (this.connectTimeout >= 0) {
            connection.setConnectTimeout(this.connectTimeout);
        }

        if (this.readTimeout >= 0) {
            connection.setReadTimeout(this.readTimeout);
        }

        connection.setDoInput(true);
        if ("GET".equals(httpMethod)) {
            connection.setInstanceFollowRedirects(true);
        } else {
            connection.setInstanceFollowRedirects(false);
        }

        if (!"POST".equals(httpMethod) && !"PUT".equals(httpMethod) && !"PATCH".equals(httpMethod) && !"DELETE".equals(httpMethod)) {
            connection.setDoOutput(false);
        } else {
            connection.setDoOutput(true);
        }

        connection.setRequestMethod(httpMethod);
    }
}



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用`RestTemplate`的`postForEntity`方法来发送HTTP POST请求,同时携带文件流和其他参数。具体可以参考下面的示例代码: ```java import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class RestClient { public static void main(String[] args) throws IOException { String url = "http://example.com/upload"; // 设置请求HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 设置请求体 MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); // 添加文件流 Path filePath = Paths.get("path/to/file.txt"); byte[] fileBytes = Files.readAllBytes(filePath); Resource fileResource = new ByteArrayResource(fileBytes) { @Override public String getFilename() { return filePath.getFileName().toString(); } }; body.add("file", fileResource); // 添加其他参数 body.add("param1", "value1"); body.add("param2", "value2"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class); System.out.println(response.getBody()); } } ``` 在上面的示例代码中,我们首先设置了请求头,指定了请求体的类型为`multipart/form-data`。然后构造了一个`MultiValueMap`对象,用于存储请求体的键值对。通过`ByteArrayResource`类可以将文件流转化为Spring的`Resource`对象,并将其添加到请求体中。最后,我们使用`postForEntity`方法发送HTTP POST请求,并将响应的内容解析为字符串。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值