【问题标题】:convert curl request into URLConnection将 curl 请求转换为 URLConnection
【发布时间】:2015-04-25 01:50:39
【问题描述】:

我有这个cURL 请求:

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-X PUT https://api.twitch.tv/kraken/users/<bot_name>/follows/channels/<channel_name>

我需要将其转换为 Java URLConnection 请求。这是我到目前为止所拥有的:

String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);

conn.setRequestMethod("PUT");

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write("https://api.twitch.tv/kraken/users/" + bot.botName + "/follows/channels/" + gamrCorpsTextField.getText());
out.close();

new InputStreamReader(conn.getInputStream());

任何帮助将不胜感激!

【问题讨论】:

    标签: java http curl put


    【解决方案1】:

    您准备在此代码中打开的网址:

    String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());
    

    与您的curl 请求网址不匹配:

    https://api.twitch.tv/kraken/users/<bot_name>/follows/channels/<channel_name>
    

    你似乎想要更像这样的东西:

    URL requestUrl = new URL("https://api.twitch.tv/kraken/users/" + bot.botName
            + "/follows/channels/" + gamrCorpsTextField.getText());
    HttpURLConnection connection = (HttpUrlConnection) requestUrl.openConnection();
    
    connection.setRequestMethod("PUT");
    connection.setRequestProperty("Accept", "application/vnd.twitchtv.v3+json");
    connection.setRequestProperty("Authorization", "OAuth <access_token>");
    connection.setDoInput(true);
    connection.setDoOutput(false);
    

    这会设置一个“URLConnection 请求”,该请求等同于 curl 命令将根据请求发出的请求。从那里您可以通过connection 对象获取响应代码、读取响应标头和正文等。

    【讨论】:

    • 谢谢!我也添加了connection.setRequestProperty("Content-Length", connection.getContentLength()+"");,但现在它抛出了java.lang.IllegalStateException: Already connected 错误。知道为什么吗?
    • 在执行任何需要发送 HTTP 请求的操作后,您将无法再设置请求属性。一种这样的操作是getContentLength(),因为它检索response 内容的长度。无论如何,您应该不需要直接设置 request 的内容长度。只需使用doOutput(true),并通过连接的OutputStream 编写请求正文。
    猜你喜欢
    • 2017-08-03
    • 2018-04-16
    • 2021-02-06
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2015-08-10
    相关资源
    最近更新 更多