我正在将 Microsoft Translator 用于需要 Jersey 发出 HTTP 发布请求的 Java 项目。我当前的代码导致 HTTP 400 错误 - 错误请求。我对 HTTP 很陌生——有人能指出我正确的方向吗?
Microsoft 访问令牌说明: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();
}
}
}