gpt4 book ai didi

java - 使用 Jersey 对 Google Translate 进行 POST 调用返回 HTTP 404

转载 作者:可可西里 更新时间:2023-11-01 16:31:20 27 4
gpt4 key购买 nike

我正在尝试使用 Jersey 1.5 编写对 Google 翻译的 POST 调用。这是我的代码:

package main;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import javax.ws.rs.core.MultivaluedMap;

public class Main {

private static String GOOGLE_TRANSLATE_URL = "https://www.googleapis.com/language/translate/v2";

private static String translateString(String sourceString, String sourceLanguage, String targetLanguage) {
String response;
Client c = Client.create();

WebResource wr = c.resource(GOOGLE_TRANSLATE_URL);
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("q", sourceString);
params.add("source", sourceLanguage);
params.add("target", targetLanguage);
params.add("key", "xxxx");
wr.header("X-HTTP-Method-Override", "GET");
response = wr.post(String.class, params);

return response;
}

public static void main(String[] args) {
System.out.println(translateString("Hello", "en", "sv"));
}
}

当我运行它时,我得到的只是:com.sun.jersey.api.client.UniformInterfaceException: POST <a href="https://www.googleapis.com/language/translate/v2" rel="noreferrer noopener nofollow">https://www.googleapis.com/language/translate/v2</a> returned a response status of 404 .

我已经通过一个简单的 cURL 命令成功完成了这个任务,如下所示:

curl --header "X-HTTP-Method-Override: GET" -d key=xxxx -d q=Hello -d source=en -d target=sv <a href="https://www.googleapis.com/language/translate/v2" rel="noreferrer noopener nofollow">https://www.googleapis.com/language/translate/v2</a>

提前致谢!

最佳答案

我怀疑 Content-Length 为零的 POST 不是普通 HTTP 服务器会接受的。 RFC 没有定义这种情况,但 POST 的主要假设是您正在发送消息正文。

查看 Google API , 他们提到了以下内容

You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).

这意味着您不需要在 URL 中添加 q、source 和 target 参数,而是需要在 POST 正文中这样做。我不熟悉 Jersey API,简单看一下,您只需将 params 作为显式第二个参数添加到 .post 调用,删除 queryParams() 调用,并正确设置 Content-Length。

关于java - 使用 Jersey 对 Google Translate 进行 POST 调用返回 HTTP 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4756744/

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