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();
Related
i am trying to convert the following curl to java and i get the error 400
400 Request body must be an array. The request body is not an array.
curl -v -X POST 'https://api.openfigi.com/v1/mapping'
--header 'Content-Type: text/json'
--data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'
public void r2() throws MalformedURLException, IOException {
//String str = "https://www.openfigi.com/search#!?marketSector=Comdty";
String str = "https://api.openfigi.com/v1/mapping";
URL url = new URL(str);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/json");
String input = "'[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]'";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
/*
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}*/
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
thanks
The program work as expected after removing the ' character in the beginning and ending of input.
String input = "[{\"idType\":\"ID_WERTPAPIER\",\"idValue\":\"851399\",\"exchCode\":\"US\"}]";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
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());
I'm working with New Relic REST API for the first time, I have a curl command:
curl -X GET 'https://api.newrelic.com/v2/applications/appid/metrics/data.json' \
-H 'X-Api-Key:myApiKey' -i \
-d 'names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp'
I want to send this command in a java servlet and get a JSON object from the response ready for parsing, What is the best solution?
HttpURLConnection?
Apache httpclient?
I've tried a few different solutions, but nothing has worked so far and most examples I could find are using the depreciated DefaultHttpClient
Here is an example of one of my attempts:
String url = "https://api.newrelic.com/v2/applications.json";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-Api-Key", "myApiKey");
conn.setRequestMethod("GET");
JSONObject names =new JSONObject();
try {
names.put("names[]=", "EndUser/WebTransaction/WebTransaction/JSP/index.jsp");
} catch (JSONException e) {
e.printStackTrace();
}
OutputStreamWriter wr= new OutputStreamWriter(conn.getOutputStream());
wr.write(names.toString());
Edit
I've modified the code a bit, it's working now thanks.
String names = "names[]=EndUser/WebTransaction/WebTransaction/JSP/index.jsp";
String url = "https://api.newrelic.com/v2/applications/myAppId/metrics/data.json";
String line;
try (PrintWriter writer = response.getWriter()) {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("X-Api-Key", "myApiKey");
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(names);
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.println(HTML_START + "<h2> NewRelic JSON Response:</h2><h3>" + line + "</h3>" + HTML_END);
}
wr.close();
reader.close();
}catch(MalformedURLException e){
e.printStackTrace();
}
curl -d sends whatever you specify without formatting it in any way. Just send the string names[]=EndUser/... in the OutputStream, without wrapping it in a JSONObject. Don't forget to call wr.flush() after writing the string. And of course, after that, you need to get the InputStream and start reading from it (I only mention this because it's not in your snippet).
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.
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");