Framework & Platform/Spring

spring - restTemplate example

linuxism 2014. 9. 12. 10:03

you can do it like this:


Code:

public void post() {

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

    map.add("name", "xx");

    map.add("password", "xx");

    String result = rest.postForObject("http://localhost:8080/soa-server/user/", map, String.class);

    System.out.println(result);

}


and before you use resttemplate you must init it :

Code:

RestTemplate rest = new RestTemplate();

HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();

HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();

rest.setMessageConverters(new HttpMessageConverter[]{formHttpMessageConverter, stringHttpMessageConverternew});


my english is not very good , sorry. I do not know can you understand me

Last edited by oakeye; Nov 24th, 2009, 06:40 PM.



source - http://forum.spring.io/forum/spring-projects/web/70845-sending-post-parameters-with-resttemplate-requests








HttpClient with SSL

If you're new here, you may want to get my "Spring Security for REST" eBook. Thanks for visiting!

1. Overview

This article will show how to configure the Apache HttpClient 4 with SSL support. The goal is simple – consume HTTPS URLs which do not have valid certificates.

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.

2. The SSLPeerUnverifiedException

Without configuring SSL with the HttpClient, the following test – consuming an HTTPS URL – will fail:

1
2
3
4
5
6
7
8
9
10
11
12
public class HttpLiveTest {
 
    @Test(expected = SSLPeerUnverifiedException.class)
    public void whenHttpsUrlIsConsumed_thenException()
      throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String urlOverHttps = "https://localhost:8080/spring-security-rest-basic-auth";
        HttpGet getMethod = new HttpGet(urlOverHttps);
        HttpResponse response = httpClient.execute(getMethod);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    }
}

The exact failure is:

1
2
3
4
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:126)
    ...

The javax.net.ssl.SSLPeerUnverifiedException exception occurs whenever a valid chain of trust couldn’t be established for the URL.

3. Configure SSL – Accept All (HttClient < 4.3)

Let’s now configure the http client to trust all certificate chains regardless of their validity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
public void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException()
  throws IOException, GeneralSecurityException {
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };
    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy,
      SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 8443, sf));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
 
    DefaultHttpClient httpClient = new DefaultHttpClient(ccm);
 
    HttpGet getMethod = new HttpGet(urlOverHttps);
    HttpResponse response = httpClient.execute(getMethod);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

With the new TrustStrategy now overriding the standard certificate verification process (which should consult a configured trust manager) – the test now passes and the client is able to consume the HTTPS URL.

4. The Spring RestTemplate with SSL (HttpClient < 4.3)

Now that we have seen how to configure a raw HttpClient with SSL support, let’s take a look at a more high level client – the Spring RestTemplate.

With no SSL configured, the following test fails as expected:

1
2
3
4
5
6
7
@Test(expected = ResourceAccessException.class)
public void whenHttpsUrlIsConsumed_thenException() {
    ResponseEntity<String> response =
      new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

So let’s configure SSL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
 
...
@Test
public void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenException()
  throws GeneralSecurityException {
    HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory();
    DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory.getHttpClient();
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
    @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };
    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));
 
    ResponseEntity<String> response = new RestTemplate(requestFactory).
      exchange(urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

As you can see, this is very similar to the way we configured SSL for the raw HttpClient – we configure the request factory with SSL support and then we instantiate the template passing this preconfigured factory.

5. Conclusion

This tutorial discussed how to configure SSL for an Apache HttpClient so that it is able to consume any HTTPS URL, regardless of the certificate. The same configure for the Spring RestTemplate is also illustrated.

An important thing to understand however is that this strategy entirely ignores certificate checking– which makes it insecure and only to be used where that makes sense.

The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.



source - http://www.baeldung.com/httpclient-ssl



* 최신 버전에서 에러 발생








Using RestTemplate with Basic Auth

Recently I was trying to write integration tests using Spring’s RestTemplate to make REST calls to an integration server. The server was secured using basic auth over https, and the SSL certificate was a self-signed cert created for development use only. I wanted to use RestTemplate to retrieve JSON objects and convert them to POJO’s for asserting values in the test. However it turned out that most of the examples online did not deal with this particular scenario or were out of date. So here is how to use Spring 4’s RestTemplate with the latest Apache HTTPClient (version 4.3.1 as of this writing) over HTTPS.

One complication was that the cert was self-signed. This is easily acceptable if using curl with the “-k” option, but with RestTemplate it requires a little more work to accept the cert.

Spring’s RestTemplate integrates with Apache HttpClient, it’s just the HttpClient that needs to be configured with the username, password, and to accept an insecure cert. Here is the code:

1
2
3
4
5
6
7
8
9
10
11
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "mypassword"));
 
HttpClient httpClient = HttpClientBuilder.create()
                                        .setSSLSocketFactory(connectionFactory)
                                        .setDefaultCredentialsProvider(credentialsProvider)
                                        .build();
 
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

Finally, the request factory is used to construct a new RestTemplate which can make the call to the server.

1
2
3
4
5
RestTemplate template = new RestTemplate(requestFactory);
ResponseEntity<User> response = template.postForEntity("https://localhost:8000/path/to/user/1", "", User.class);
User userResponse = response.getBody();
 
assertEquals(1L, userResponse.getId());

Fortunately the test passes… now we can run integration tests with JUnit at will! Happy Testing!



source - http://thoughtfulsoftware.wordpress.com/2014/01/12/using-resttemplate-with-basic-auth/