convert curl request into URLConnection - java

I have this cURL request:
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>
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());
Any help will be appreciated!

The URL you are preparing to open in this code:
String url = "https://api.twitch.tv/kraken/?oauth_token=" + bot.botOAuth.substring("oauth:".length());
does not match your curl request URL:
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);
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.

Related

400 Error Paypal Token API with Java (HttpURLConnection)

I am trying to integrate Paypal using Jave(using HttpURLConnection)
API for getting token in Paypal
JDK version-1.8
Requirements:
Basic Auth Authentication -username and password.
Copied the value from Postman and added as Authentication in Header.
Body - grant_type=client_credentials as application/x-www-form-urlencoded
Adding my code:
String url = "https://api.sandbox.paypal.com/v1/oauth2/token";
HttpURLConnection con = null;
BufferedReader in = null;
String response = "";
String urlParameters="";
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("POST");
urlParameters = "grant_type=client_credentials";
//add request header
con.setRequestProperty("authorization", "Basic Value");
con.setRequestProperty("content-type","application/x-www-form-urlencoded");
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
// For POST only - START
OutputStream os = con.getOutputStream();
os.flush();
os.close();
I am getting a 400 error for all API requests.
Please help.
Is this the correct way to add the body part.

curl response is different from the responce of java.net.URL

curl -v https://whatwg.org/html
header is:
HTTP/1.1 301 Moved Permanently
Location: https://html.spec.whatwg.org/multipage
however..
String link = "https://whatwg.org/html";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int status = conn.getResponseCode();
System.out.println("Response Code ... " + status);
Response Code ... 200
The first and second results are different, what I am doing wrong and how should I receive 301 ?

HTTP Post message for firebase in Java

I would like to send a notification from my Java program to Firebase. But I don't know how to do that.
In order to send a notification using curl:
# api_key=YOUR_SERVER_KEY
# curl --header "Authorization: key=$api_key" \
--header Content-Type:"application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"registration_ids\":[\"ABC\"]}"
I want the equivalent of that in Java. I tried the following but it is not correct
String rawData = "{\"registration_ids\":[\"ABC\"]}";
String encodedData = URLEncoder.encode( rawData, "UTF-8" );
URL u = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key="+api_key);
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());

How to Pass Username and Password in GET Request in Java

Below is the Code Written by me.
But when i send the request i am getting Response Code 401 : Unathorized.
String url = "SAMPLE_URL";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
//con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
Add this code to your program after obj.openConnection();
String encoded = Base64.encode(username+":"+password);
con.setRequestProperty("Authorization", "Basic "+encoded);

java HttpsURLConnection

I tried to make this curl request executable from Java:
curl -H 'Accept: application/vnd.twitchtv.v2+json' \
-d "channel[status]=testing+some+stuff" \
-X PUT https://api.twitch.tv/kraken/channels/testacc222?oauth_token=6e7b9cyfi8zk1gr8g06eecebnitlcvb
My solution looks like this:
public static void main(String args[]) throws IOException {
String uri = "https://api.twitch.tv/kraken/channels/testacc222?oauth_token=6e7b9cyfi8zk1gr8g06eecebnitlcvb";
URL url = new URL(uri);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/vnd.twitchtv.v2+json");
String data = "channel[status]=testing";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.flush();
for (Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
}
I don't see any problem yet all it returns is:
Status=[400 Bad Request]
null=[HTTP/1.1 400 Bad Request]
Server=[nginx]
X-Request-Id=[ccc7a9a4a327b18ea4bf496f1f314fb8]
X-Runtime=[0.032328]
Connection=[keep-alive]
X-MH-Cache=[appcache1; M]
Date=[Sun, 06 Jul 2014 14:07:49 GMT]
Via=[1.1 varnish]
Accept-Ranges=[bytes]
X-Varnish=[2778442693]
X-UA-Compatible=[IE=Edge,chrome=1]
Cache-Control=[max-age=0, private, must-revalidate]
Vary=[Accept-Encoding]
Content-Length=[83]
Age=[0]
X-API-Version=[2]
Content-Type=[application/json; charset=utf-8]
I'm trying to figure this out for over a week now and I just don't see the mistake. Any help whatsoever would be greatly appreciated.
Try examining the response body, as it probably contains details about the rejection. Since the Content-Type specifies utf-8, you can create an InputStreamReader using that:
try (Reader response =
new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8)) {
int c;
while ((c = response.read()) >= 0) {
System.out.print((char) c);
}
}
Update: The response body states that the 'channel' parameter isn't present. This is because curl automatically encodes the POST data as application/x-www-form-urlencoded, but your code does not. You'll need to use URLEncoder on your data and also set the request's Content-Type:
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/vnd.twitchtv.v2+json");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = "channel[status]=testing";
data = URLEncoder.encode(data, "UTF-8");

Categories

Resources