java - 如何使用java复制curl命令?
问题描述
准确地说,我想执行以下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
Response Code : 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 请求或其他类型的非预期内容将导致请求不匹配。删除额外的输出内容并试一试!
推荐阅读
- c - 在函数中分配内存,然后在外部使用
- reactjs - 我无法启动 React 项目,因为 node_models 文件丢失但它们存在
- flutter - 为什么选定的值没有反映在 showModalBottomSheet 中?
- angular - 无论时区如何,都使用绝对日期
- tree - ggtree:彩色树枝和尖端
- substrate - 错误[E0658]:非内置内部属性不稳定
- php - 在 null 上调用成员函数 getBag() - Laravel
- r - 仅通过增加 R 中的升序来过滤组
- python - 列表的乘积函数
- typescript - Typescript 在返回类型中引用自己的类型方法