gpt4 book ai didi

java - 将 Microsoft Translator 与 Java/Jersey/REST 一起使用

转载 作者:行者123 更新时间:2023-11-30 11:43:56 25 4
gpt4 key购买 nike

我正在将 Microsoft Translator 用于需要 Jersey 发出 HTTP 发布请求的 Java 项目。我当前的代码导致 HTTP 400 错误 - 错误请求。我是 HTTP 的新手 - 有人能给我指出正确的方向吗?

Microsoft 访问 token 说明: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();
}
}
}

最佳答案

将数据发送到 token 服务时,您需要使用 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);

关于java - 将 Microsoft Translator 与 Java/Jersey/REST 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com