如何使用Spring RestTemplate

时间:2017-02-19 06:46:23

标签: rest

我正在使用Tomcat7,Sprng框架来提供restfull Web服务。我试图使用Spring RestTemplate调用具有基本身份验证的http Web服务。

我无法让它发挥作用。任何人都可以根据下面的代码告诉我我需要更改什么才能调用具有基本身份验证的http restfull Web服务。也可以有人告诉我或者提供pom.xml文件哪个java库我需要吗?

import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.journaldev.spring.controller.EmpRestURIConstants;
import com.journaldev.spring.model.CostControlPost;
import com.journaldev.spring.model.Employee;
import com.journaldev.spring.model.RfxForUpdate;

import static org.junit.Assert.*;
import org.apache.commons.codec.binary.Base64;

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class TestExample2 {

    public static final String SERVER_LIST="http://abc/sourcing/testServices";


    @Test
    public void testGetListOfServiceNames()
    {
        try
        {               
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.exchange(SERVER_LIST,HttpMethod.GET,null,String.class);
            assertNotNull(response);    
        }
        catch(Exception e)
        {
            System.out.println("e:"+e.getMessage());
        }
    }                   
 }

1 个答案:

答案 0 :(得分:2)

以最简单的形式:

    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider =  new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password);
    httpClient.setCredentialsProvider(credentialsProvider);
    ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);

    template = new RestTemplate(rf);

Spring自动管理:

为RestTemplate创建HTTP上下文:

 private HttpContext createHttpContext() {
        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }

添加拦截器:

restTemplate.getInterceptors().add(
  new BasicAuthorizationInterceptor("username", "password"));

呼叫:

restTemplate.exchange(
  "http://abc/sourcing/testServices", 
  HttpMethod.GET, null, String.class);

参考this帖子。