2012-06-14 60 views
2

我正在使用Microsoft Translator for Java项目,该项目要求Jersey发出HTTP发布请求。我当前的代码导致HTTP 400错误 - 错误的请求。我对HTTP很陌生 - 有人能指出我正确的方向吗?在Java/Jersey/REST中使用Microsoft Translator

微软访问令牌说明:http://msdn.microsoft.com/en-us/library/hh454950

package com.mkyong.client; 

    import com.sun.jersey.api.client.Client; 
    import java.net.*; 

    import javax.ws.rs.core.EntityTag; 
    import javax.ws.rs.core.MediaType; 

    import com.sun.jersey.api.client.ClientResponse; 
    import com.sun.jersey.api.client.WebResource; 

    public class JerseyClientPost { 

public static void main(String[] args) { 

    try { 

     Client client = Client.create(); 

     WebResource webResource = client 
        .resource("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"); 
     //Paramaters for Access Token 
     //String inpu2t = "{\"Tyler_Kevin\",\"VcwDLMGuFMLnUgql...\",\"http://api.microsofttranslator.com\",\"client_credentials\"}"; 

     String input = "{\"client_id\":\"Tyler_Kevin\",\"client_secret\":\"VcwDLMGuFMLnUgqldjrfj....",\"scope\":\"http://api.microsofttranslator.com\",\"grant_type\":\"client_credentials\"}"; 

     //Send HTTP POST request to Microsoft Server 
     ClientResponse response = webResource.type("application/json") 
       .post(ClientResponse.class, input); 


     //If request is not successful, throw error 
     if (response.getStatus() != 201) { 
      throw new RuntimeException("Failed =/ : HTTP error code : " 
        + response.getStatus()); 
     } 

     //Display server response 
     System.out.println("Output from Server .... \n"); 
     String output = response.getEntity(String.class); 
     System.out.println(output); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 

回答

1

您需要使用应用程序/ x-WWW的形式了urlencoded的数据发送到令牌服务时。所以我想尝试以下方法:

com.sun.jersey.api.representation.Form input = new Form(); 
input.add("client_id", "Tyler_Kevin"); 
input.add("client_secret", "VcwDLMGuFMLnUgqldj....."); 
input.add("scope", "http://api.microsofttranslator.com"); 
input.add("grant_type", "client_credentials"); 

// send HTTP POST 
ClientResponse response = webResource.type("application/x-www-form-urlencoded") 
     .post(ClientResponse.class, input); 
+0

不幸的是,我仍然得到一个400错误。 –

+0

更新 - “应用程序”仅在webResource.type(“applicatin”...)行中被拼写错误。修正它完美的作品。感谢您的帮助! –

相关问题