RestTemplate中的三种请求方式postForObject、postForEntity、exchange

启动类配置参数

@SpringBootApplication
@EnableDiscoveryClient
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

测试类

	public static void main(String[] args) {
		RestTemplate template = new RestTemplate();
    	String url = "http://127.0.0.1:12813/member/c2/f02";
    	// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
    	MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
    	paramMap.add("dt", "{\"uscInfo\":{\"member\":\"123\",\"isEncrypt\":0,\"tenant\":\"456\",\"devciceIp\":\"789\",\"devciceId\":\"147\"},\"quInfo\":{\"account\":\"258\",\"pushId\":\"369\",\"optSys\":\"159\",\"code\":\"357\",\"addressProvince\":\"153\",\"addressRegion\":\"183\",\"businessType\":\"486\",\"addressCity\":\"759\",\"codeKey\":\"726\"} }");
    	postForObject(template, paramMap, url);
    	postForEntity(template, paramMap, url);
    	exchange(template, paramMap, url);
	}
	public static String postForObject(RestTemplate template,MultiValueMap<String, Object> paramMap,String url){
    	// 1、使用postForObject请求接口
    	String result = template.postForObject(url, paramMap, String.class);
    	System.out.println("result1==================" + result);
    	return result;
    }
	public static String postForEntity(RestTemplate template,MultiValueMap<String, Object> paramMap,String url){
    	HttpHeaders headers = new HttpHeaders();
    	HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
    	ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
    	System.out.println("result2====================" + response2.getBody());
    	return response2.getBody();
    }
	public static String exchange(RestTemplate template,MultiValueMap<String, Object> paramMap,String url) {
		HttpHeaders headers = new HttpHeaders();
    	HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
    	ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
		System.out.println("result3====================" + response3.getBody());
		return response3.getBody();
	}

附加1:请求类型为jsonString

		RestTemplate template = new RestTemplate();
		String url = "http://127.0.0.1:12813/member/c2/f02";
		/*MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
    	paramMap.add("dt", req);*/
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_JSON);
    	headers.add("t", "she0827e6e83744a6b89624ae053dfc847");
    	HttpEntity<String> httpEntity = new HttpEntity<String>(req,headers);
    	
    	ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
    	return response2.getBody();

附加2:发起https请求(HTTPS请求 = 超文本传输协议HTTP + 安全套接字层SSL)
先创建SimpleClientHttpRequestFactory的实现类HttpsClientRequestFactory.java

package com.sgcc.service.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

/**
 * 声明:此代码摘录自https://blog.csdn.net/wltsysterm/article/details/80977455
 * 声明:关于Socket的相关知识,本人会在后面的闲暇时间进行学习整理,请持续关注博客更新
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
	
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        try {
            if (!(connection instanceof HttpsURLConnection)) {
                throw new RuntimeException("An instance of HttpsURLConnection is expected");
            }
 
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
 
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
						@Override
						public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
								throws CertificateException {
							// TODO Auto-generated method stub
							
						}
						@Override
						public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
								throws CertificateException {
							// TODO Auto-generated method stub
							
						}
 
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
 
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
 
            super.prepareConnection(httpsConnection, httpMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
     * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
     */
    // SSLSocketFactory用于创建 SSLSockets
    private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
 
        private final SSLSocketFactory delegate;
 
        public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }
 
        // 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
        // 这些默认的服务的最低质量要求保密保护和服务器身份验证
        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }
 
        // 返回的密码套件可用于SSL连接启用的名字
        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }
 
 
        @Override
        public Socket createSocket(final Socket socket, final String host, final int port, 
        		final boolean autoClose) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
            return overrideProtocol(underlyingSocket);
        }
 
 
        @Override
        public Socket createSocket(final String host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final String host, final int port, final InetAddress localAddress, 
        		final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final InetAddress host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, 
        		final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }
 
        private Socket overrideProtocol(final Socket socket) {
            if (!(socket instanceof SSLSocket)) {
                throw new RuntimeException("An instance of SSLSocket is expected");
            }
            ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
            return socket;
        }
    }
}

再编写调用方法

public String RestTemplate(String req){
		RestTemplate template = new RestTemplate(new HttpsClientRequestFactory());
		String url = "https://127.0.0.1:12813/member/c2/f02";
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_JSON);
    	headers.add("t", "sh0fe976d6c1474ca7b185dbd87e201f13");
    	HttpEntity<String> httpEntity = new HttpEntity<String>(req,headers);
    	
    	ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
    	return response2.getBody();
	}
  • 11
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RestTemplateexchange方法是一个HTTP请求方法,用于发送HTTP请求并接收响应。该方法提供了灵活的参数配置,可以指定HTTP方法、请求URL、请求头、请求体和响应类型等。 通常情况下,我们可以通过以下方式使用exchange方法: 1. 创建一个RestTemplate对象。 2. 使用exchange方法发送HTTP请求,并传入请求方法、URL、请求体、请求头和响应类型等参数。 3. 接收并处理返回的响应。 以下是一个使用exchange方法的示例代码: ```java RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); HttpEntity<String> requestEntity = new HttpEntity<>("request body", headers); ResponseEntity<String> responseEntity = restTemplate.exchange("http://api.example.com/endpoint", HttpMethod.POST, requestEntity, String.class); String responseBody = responseEntity.getBody(); ``` 在上述示例,我们创建了一个RestTemplate对象,并设置了请求头和请求体。然后使用exchange方法发送了一个POST请求到指定的URL,并指定了响应类型为String。最后,我们可以通过responseEntity对象获取到返回的响应体。 需要注意的是,exchange方法的参数类型需要根据实际情况进行调整。例如,如果请求体是一个复杂的嵌套对象,可以使用对应的类作为请求体参数的类型。 总结起来,exchange方法是RestTemplate用于发送HTTP请求并接收响应的方法,可以根据需要进行参数配置,并根据响应类型进行结果处理。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [RestTemplateexchange发起请求](https://blog.csdn.net/weixin_40120559/article/details/131618296)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [RestTemplate使用实战-exchange方法讲解](https://blog.csdn.net/zxh1991811/article/details/102744155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值