如何使用Rest Template强制TLS1.2到Rest客户端

时间:2016-08-26 08:16:27

标签: java spring resttemplate tls1.2

我通过调用post方法使用Spring3.0 restTemplate来使用json webservice。

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);      
        HttpEntity<Object> entity = new HttpEntity<Object>(requestAsString, headers);
        postForObject = restTemplate.postForObject(url, entity, responseClass );

我们的应用程序部署在WAS服务器中,并尝试通过创建与TLS1.0的套接字连接来连接生产者。但是,现在生产者只支持TLS1.1和TLS1.2。

如何强制restTempate使用TLS1.1或TLS 1.2。

通常对于apache httpclient代码,创建自定义ProtocolSocketFactory并覆盖createSocket方法。但是,在RestTemplate的情况下,如何实现相同。

3 个答案:

答案 0 :(得分:19)

使用Spring&gt; 3.1:

import javax.net.ssl.SSLContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(null, null, null);

CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(context)
    .build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
.....

答案 1 :(得分:5)

您可以将RestTemplate配置为使用自定义ClientHttpRequestFactory。特别是(因为你使用的是Spring 3.0),有一个CommonsClientHttpRequestFactory。这将使您能够详细配置公共HTTP,并且您的RestTemplate将使用它来执行其请求。

请注意,实际的实现类在Spring的更高版本中已经更改(如果你仍然在3.0上,你真的应该考虑更新)。从3.1开始,实现类称为HttpComponentsClientHttpRequestFactory

答案 2 :(得分:0)

如果您想设置多个有效的 TLS 版本,请使用 import SwiftUI struct ImportCSVView: View { @State private var openFile = false @State private var fileName = "" @State private var fileUrl = "" @State var importComplete = false @State var newData = [PersonModel]() @ObservedObject var dm : DataManager var body: some View { Form { Section { //code } Section { Button(action: { openFile.toggle() }, label: { Text("Import .csv file") } } }.fileImporter(isPresented: self.$openFile, allowedContentTypes: [.commaSeparatedText]) { (result) in do { let fileURL = try result.get() self.fileName = fileURL.lastPathComponent self.fileUrl = fileURL.path if fileUrl != "" { var data = "" do { data = try String(contentsOfFile: fileUrl) } catch { print(error) return } var rows = data.components(separatedBy: "\n") for row in rows { let columns = row.components(separatedBy: ",") if columns.count == 4 { let name = columns[0] let surname = columns[1] let phoneNumber = columns[2] let address = columns[3] let prs = PersonModel(name: name, surname: surname, phoneNumber: phoneNumber, address: address) newData.append(prs) for newPeople in newData { dm.storagePeople.append(newPeople) } importComplete = true } } } } catch { print(error.localizedDescription) } } 。例如,如果您想支持 TLSv1.2 和 TLSv1.3:

SSLConnectionSocketFactory