HTTP Post message for firebase in Java - 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());

Related

server returns java.io.IOException: Server returned HTTP response code: 400 for URL

I am trying to call rest API which is documented like this
curl -X POST "https://url/api/v1/className/doSomething" -H "accept: application/json" -H "Authorization: Bearer token" -H "Content-Type: application/json" -d
Here is my code sends http post. It works good with all http apis I used before but not for this.
String result = "";
RequestProcess process = LogManager.getInstance().newProcess();
process.setProcessName(url);
process.setRequestContent(requestContent);
ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module()).registerModule(new JavaTimeModule());
String rawData = mapper.writeValueAsString(requestContent);
String charset = "UTF-8";
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setRequestMethod("POST");
try (OutputStream output = connection.getOutputStream()) {
output.write(rawData.getBytes(charset));
}
InputStream inputStream = connection.getInputStream();
result = StreamUtil.toString(inputStream);
process.setResponseContent(result);
LogManager.getInstance().endProcess(process);
return result;
I am getting an error
java.io.IOException: Server returned HTTP response code: 400 for URL: url
I tried to do the same from postman and it works. Any ideas?
What do you send as Data? at least you should send -d {} for empty data or remove -d
If it is running in POSTMAN, you can get the corresponding curl
request from it. By clicking on Code and select cURL from available options.
I've solved it by removing charset in the Content-Type section.
After modification this line looks like this
connection.setRequestProperty("Content-Type", "application/json");

convert curl request into URLConnection

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.

How do i do the following curl command in Java

How would I implement the following curl command in Java URLConnection
curl -X PUT \
-H "X-Parse-Application-Id: " \
-H "X-Parse-REST-API-Key: " \
-H "Content-Type: application/json" \
-d '{"score":73453}'
Thanks in advance
Using the derived class of URLConnection which is HttpURLConnection you can easily do it.
URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
myURLConnection.setRequestMethod("PUT");
myURLConnection.setRequestProperty("X-Parse-Application-Id", "");
myURLConnection.setRequestProperty("X-Parse-REST-API-Key", "");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("score", "73453");
OutputStream os = myURLConnection.getOutputStream();
os.write(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
os.close();
For curl -X GET \ -H "X-Parse-Application-Id: " \ -H "X-Parse-REST-API-Key: " \ -G \ --data-urlencode 'include=game
String charset = "UTF-8";
String query = String.format("include=%s", URLEncoder.encode("game", charset));
URL myURL = new URL(serviceURL+"?"+query);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("X-Parse-Application-Id", "");
myURLConnection.setRequestProperty("X-Parse-REST-API-Key", "");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.connect();

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

cURL and HttpURLConnection - Post JSON Data

How to post JSON data using HttpURLConnection? I am trying this:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
StringReader reader = new StringReader("{'value': 7.5}");
OutputStream os = httpcon.getOutputStream();
char[] buffer = new char[4096];
int bytes_read;
while((bytes_read = reader.read(buffer)) != -1) {
os.write(buffer, 0, bytes_read);// I am getting compilation error here
}
os.close();
I am getting compilation error in line 14.
The cURL request is:
curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "{'value': 7.5}" \
"a URL"
Is this the way to handle cURL request? Any information will be very helpful to me.
Thanks.
OutputStream expects to work with bytes, and you're passing it characters. Try this:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
You may want to use the OutputStreamWriter class.
final String toWriteOut = "{'value': 7.5}";
final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(toWriteOut);
osw.close();

Categories

Resources