2

我正在将 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();
    }
}
}
4

1 回答 1

1

将数据发送到令牌服务时,您需要使用 application/x-www-form-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);
于 2012-06-14T12:37:53.677 回答