2015-04-25 150 views
1

我有這樣的要求cURL轉換捲曲請求轉換的URLConnection

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

任何幫助將不勝感激!

回答

1

你準備在這個代碼打開URL:

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

不符合您的curl請求URL:

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對象讀取響應標題和正文等等。

+0

謝謝!我添加了'connection.setRequestProperty(「Content-Length」,connection.getContentLength()+「」);'現在它拋出了一個'java.lang.IllegalStateException:Already connected'錯誤。任何想法爲什麼? –

+0

執行任何需要發送HTTP請求的操作後,您不能再設置請求屬性。一個這樣的操作是'getContentLength()',因爲它檢索* response *內容的長度。無論如何您都不需要直接設置* request *的內容長度。只需使用'doOutput(true)',並通過連接的'OutputStream'寫入請求體。 –