2015-03-25 64 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

相关问题