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 paramMap = new LinkedMultiValueMap();
    	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();
	}

你可能感兴趣的:(RestTemplate中的三种请求方式postForObject、postForEntity、exchange)