2015-03-25 67 views
0

我想JSON數據發送到一個REST服務,其中包括認證,但是當我嘗試運行這段代碼,它拋出一個RuntimeException和HTTP代碼302。但是鏈接通過REST客戶端正常工作。我認爲我的代碼無法將驗證細節提供給鏈接。發送POST數據到REST服務與認證

我已經嘗試了這麼多的組合,但它仍然沒有工作。任何人都可以建議我去哪裏錯了嗎?

JSONObject obj=new JSONObject(req); //JSON Object 
ClientConfig clientConfig = new DefaultClientConfig(); 
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, 
     Boolean.TRUE); 
Client client = Client.create(clientConfig); 
//Authentication filter 
client.addFilter(new HTTPBasicAuthFilter("username", "password")); 
WebResource webResource = client.resource(
     "http://licruleswb-dev.cloudapps.cisco.com/LicenseRules/rest/invokeRule"); 
ClientResponse response = webResource.accept("application/json").type(
     MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, obj.toString()); 
if (response.getStatus() != 200) { 
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); 
} 

這是錯誤:

ERROR:Exception in thread "main" java.lang.RuntimeException: Failed : 
     HTTP error code : 302 
    at Test2.main(Test2.java:64) 

Test2的是我的課。

+2

'302'通常表示重定向。嘗試設置'client.setFollowRedirects(Boolean.TRUE);'。 – user432 2015-03-25 08:17:04

+0

你嘗試通過'http:// licruleswb-dev.cloudapps.cisco.com/LicenseRules/REST/invokeRule'是很容易得到從那裏你的代碼運行的服務器? – mario 2015-03-26 15:52:45

+0

ya..It的工作完美fine..I已經試過很多次 – user3564975 2015-03-27 06:12:40

回答

0

您正在使用什麼框架?澤西?您可以嘗試設置基本身份驗證:

Authenticator.setDefault(new Authenticator() { 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication("username", "password".toCharArray()); 
      } 
}); 
+0

沒有,我沒有使用任何framework.I試過上述方法also.But,這不是爲我工作。 – user3564975 2015-03-25 09:25:52

+0

你確定這不是球衣嗎?客戶端和WebResource類從哪裏來? – 2015-03-25 09:33:38

+0

哦sorry.these類是從com.sun.jersey到來。*包 – user3564975 2015-03-26 06:10:43

0

看起來您使用的是Jersey REST客戶端。您需要知道,此方法在版本2.5中已被棄用,並在版本2.6中被刪除。在更高版本的新澤西,你需要使用這樣的:

// Send with all calls 
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(
               "username", "password"); 

// Send with a single call 
Response response = client.target("http://...").request() 
    .property(HTTP_AUTHENTICATION_BASIC_USERNAME, "username") 
    .property(HTTP_AUTHENTICATION_BASIC_PASSWORD, "password").get(); 

有關詳細信息,請參閱此鏈接:https://jersey.java.net/documentation/latest/client.html#d0e5181

您可以在您的應用程序中啓用跟蹤或使用外部HTTP代理(如tcpmon)查看實際發送的請求(如果存在包含內容的標頭Authorization)。

希望它可以幫助你, 蒂埃裏

+0

這是使用org.glassfish包,因爲我有使用Java 1.5這不是我的代碼兼容。你能建議我一些其他的事情嗎? – user3564975 2015-03-26 06:13:39

相關問題