首页 > 解决方案 > 如何使用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

非常感谢所有答复。

标签: javajsoncurl

解决方案


差不多好了!您正在执行 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 请求或其他类型的非预期内容将导致请求不匹配。删除额外的输出内容并试一试!


推荐阅读