gpt4 book ai didi

java HttpsURLConnection

转载 作者:太空宇宙 更新时间:2023-11-04 14:44:28 27 4
gpt4 key购买 nike

我试图使这个curl请求从Java可执行:

curl -H 'Accept: application/vnd.twitchtv.v2+json' \
-d "channel[status]=testing+some+stuff" \
-X PUT https://api.twitch.tv/kraken/channels/testacc222?oauth_token=6e7b9cyfi8zk1gr8g06eecebnitlcvb

我的解决方案如下所示:

public static void main(String args[]) throws IOException {

String uri = "https://api.twitch.tv/kraken/channels/testacc222?oauth_token=6e7b9cyfi8zk1gr8g06eecebnitlcvb";
URL url = new URL(uri);

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/vnd.twitchtv.v2+json");

String data = "channel[status]=testing";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.flush();
for (Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
}

我没有看到任何问题,但它返回的只是:

Status=[400 Bad Request]
null=[HTTP/1.1 400 Bad Request]
Server=[nginx]
X-Request-Id=[ccc7a9a4a327b18ea4bf496f1f314fb8]
X-Runtime=[0.032328]
Connection=[keep-alive]
X-MH-Cache=[appcache1; M]
Date=[Sun, 06 Jul 2014 14:07:49 GMT]
Via=[1.1 varnish]
Accept-Ranges=[bytes]
X-Varnish=[2778442693]
X-UA-Compatible=[IE=Edge,chrome=1]
Cache-Control=[max-age=0, private, must-revalidate]
Vary=[Accept-Encoding]
Content-Length=[83]
Age=[0]
X-API-Version=[2]
Content-Type=[application/json; charset=utf-8]

我已经尝试解决这个问题一个多星期了,但我只是没有看到错误。任何帮助将不胜感激。

最佳答案

尝试检查响应正文,因为它可能包含有关拒绝的详细信息。由于 Content-Type 指定 utf-8,因此您可以使用它创建一个 InputStreamReader:

try (Reader response =
new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8)) {

int c;
while ((c = response.read()) >= 0) {
System.out.print((char) c);
}
}

更新:响应正文指出“channel”参数不存在。这是因为 curl 自动将 POST 数据编码为 application/x-www-form-urlencoded,但您的代码不会。您需要对数据使用 URLEncoder 并设置请求的 Content-Type:

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/vnd.twitchtv.v2+json");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

String data = "channel[status]=testing";
data = URLEncoder.encode(data, "UTF-8");

关于java HttpsURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24596724/

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