2017-02-19 45 views
1

我正在使用Tomcat7,Sprng框架來提供restfull Web服務。我正在嘗試使用Spring RestTemplate調用具有基本身份驗證的http Web服務。如何使用Spring RestTemplate調用具有基本身份驗證的Restfull 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

在最簡單的形式:

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); 

春自動化管理:

爲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崗位。

相關問題