准确地说,我想执行下面的 curl
操作,它用 java 返回 json:
curl -H 'Client-ID: ahh_got_ya' -X GET 'https://api.twitch.tv/helix/streams'
这在 Linux shell 中工作得很好。
下面是我的脚本尝试使用 java json 执行上面的curl操作:
{String urly = "https://api.twitch.tv/helix/streams";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type","application/json");
con.setRequestProperty("Client-ID","Ahh_got_ya");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("");
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer jsonres = new StringBuffer();
while ((output = iny.readLine()) != null) {
jsonres.append(output);
}
iny.close();
//printing result from response
System.out.println(response.toString());
}
我得到:java.io.FileNotFoundException:https://api.twitch.tv/helix/streams
响应代码:404
非常感谢所有回复。
最佳答案
快到了!您正在进行 GET 调用,不需要使连接可写——因为您不打算发布。您需要删除该部分。另外 - 要准确了解您的curl 调用正在执行的操作,请删除Content-Type - 因为它不在curl 调用中使用。所以你的代码调整后应该是:
{
String urly = "https://api.twitch.tv/helix/streams";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//only 2 headers from cURL call
con.setRequestMethod("GET");
con.setRequestProperty("Client-ID","Ahh_got_ya");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer jsonres = new StringBuffer();
while ((output = iny.readLine()) != null) {
jsonres.append(output);
}
iny.close();
//printing result from response
System.out.println(response.toString());
}
出现 404 错误的原因是您的请求与服务端点的期望不匹配。发送 POST 请求或其他类型的非预期内容将导致请求不匹配。删除多余的输出内容并尝试一下!
关于java - 如何使用java复制curl命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575578/