将curl请求转换为URLConnection [英] convert curl request into URLConnection

查看:1598
本文介绍了将curl请求转换为URLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 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 请求。这是我到目前为止:

I need to turn it into a Java URLConnection request. This is what I have so far:

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());

任何帮助将不胜感激。

推荐答案

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

The URL you are preparing to open in this code:

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>

您似乎想要更像这样的:

You appear to want something more like this:

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 命令将根据请求发出。从那里,您可以通过连接对象获取响应代码,读取响应头和正文等。

That sets up a "URLConnection request" equivalent to the one the curl command will issue, as requested. From there you get the response code, read response headers and body, and so forth via the connection object.

这篇关于将curl请求转换为URLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆