I am using the Microsoft Translator for a Java project that requires Jersey to make an HTTP post request. My current code results in a HTTP 400 error - bad request. I am very new to HTTP- could someone point me in the right direction?

Microsoft Access Token instructions: 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();
    }
}
}
有帮助吗?

解决方案

You need to use application/x-www-form-urlencoded when sending the data to the token service. So I'd try the following:

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top