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



发布了57 篇原创文章 · 获赞 21 · 访问量 8万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览