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");
Related
I would like to run this specific curl command with a HTTP POST request in java
curl --location --request POST "http://106.51.58.118:5000/compare_faces?face_det=1" \
--header "user_id: myid" \
--header "user_key: thekey" \
--form "img_1=https://cdn.dnaindia.com/sites/default/files/styles/full/public/2018/03/08/658858-577200-katrina-kaif-052217.jpg" \
--form "img_2=https://cdn.somethinghaute.com/wp-content/uploads/2018/07/katrina-kaif.jpg"
I only know how to make simple POST requests by passing a JSON object, But i've never tried to POST based on the above curl command.
Here is a POST example that I've made based on this curl command:
curl -X POST TheUrl/sendEmail
-H 'Accept: application/json' -H 'Content-Type: application/json'
-d '{"emailFrom": "smth#domain.com", "emailTo":
["smth#gmail.com"], "emailSubject": "Test email", "emailBody":
"708568", "generateQRcode": true}' -k
Here is how i did it using java
public void sendEmail(String url) {
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
// Send post request
JSONObject test = new JSONObject();
test.put("emailFrom", emailFrom);
test.put("emailTo", emailTo);
test.put("emailSubject", emailSubject);
test.put("emailBody", emailBody);
test.put("generateQRcode", generateQRcode);
String jsonInputString = test.toString();
System.out.println(jsonInputString);
System.out.println("Email Response:" + returnResponse(con, jsonInputString));
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Mail sent");
}
public String returnResponse(HttpURLConnection con, String jsonInputString) {
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
} catch (Exception e) {
System.out.println(e);
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
return response.toString();
} catch (Exception e) {
System.out.println("Couldnt read response from URL");
System.out.println(e);
return null;
}
}
I've found this useful link but i can't really understand how to use it in my example.
Is it any different from my example? and if yes how can i POST the following data?
Note: Required Data
HEADERS:
user_id myid
user_key mykey
PARAMS:
face_det 1
boxes 120,150,200,250 (this is optional)
BODY:
img_1
multipart/base64 encoded image or remote url of image
img_2
multipart/base64 encoded image or remote url of image
Here is the complete documentation of the API
There are three things that your HttpURLConnection needs:
The request method. You can set this with setRequestMethod.
The headers. You can set them with setRequestProperty.
The content type. The HTML specification requires that an HTTP request containing a form submission have application/x-www-form-urlencoded (or multipart/form-data) as its body’s content type. This is done by setting the Content-Type header using the setRequestProperty method, just like the other headers.
It’s not clear what you’re trying to do here. As Boris Verkhovskiy points out, curl’s --form option includes data as a part of a multipart request. In your command, the content of that request would be the characters of the URLs themselves. If you really want to submit URLs, not the images at those locations, you could use an application/x-www-form-urlencoded request body to do it. The body itself needs to URL-encoded, as the content type indicates. The URLEncoder class exists for this purpose.
The steps look like this:
String img1 = "https://cdn.dnaindia.com/sites/default/files/styles/full/public/2018/03/08/658858-577200-katrina-kaif-052217.jpg";
String img2 = "https://cdn.somethinghaute.com/wp-content/uploads/2018/07/katrina-kaif.jpg";
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("user_id", myid);
con.setRequestProperty("user_key", thekey);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String body =
"img_1=" + URLEncoder.encode(img1, "UTF-8") + "&" +
"img_2=" + URLEncoder.encode(img2, "UTF-8");
try (OutputStream os = con.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input);
}
However, if you want to submit the actual images, you will need to create a MIME request body. Java SE cannot do this, but the MimeMultipart class of JavaMail, which is part of the Java EE specification, can.
Multipart multipart = new MimeMultipart("form-data");
BodyPart part;
part = new MimeBodyPart();
part.setDataHandler(new DataHandler(new URL(img1)));
multipart.addBodyPart(part);
part = new MimeBodyPart();
part.setDataHandler(new DataHandler(new URL(img2)));
multipart.addBodyPart(part);
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("user_id", myid);
con.setRequestProperty("user_key", thekey);
con.setRequestProperty("Content-Type", multipart.getContentType());
try (OutputStream os = con.getOutputStream()) {
multipart.writeTo(os);
}
You should remove all catch blocks from your code, and amend your method signatures to include throws IOException (or throws IOException, MessagingException). You don’t want users of your application to think the operation was successful if in fact it failed, right?
i want get json from this url
but get error like this :
java.io.IOException: Server returned HTTP response code: 403 for URL: http://test.dotconnect.io/data_api/reports/1bf4bc70b31d4d92b50a6d965c52fcec
this is my complete code :
InputStream is = null;
JsonReader rdr = null;
OutputStreamWriter out = null;
String path = "http://test.dotconnect.io/data_api/reports/";
int timeout = 6000000;
String key ="Authorization : 402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
URL url = new URL(path+request.getParameter("reportTaskToken"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setDoInput(true); // Triggers GET
connection.setDoOutput(true);// Triggers POST
connection.setRequestProperty("Authorization", key);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
System.setProperty("http.agent", "Chrome");
System.setProperty("http.proxyHost", "proxy.smmf.co.id");
System.setProperty("http.proxyPort", "8080");
out = new OutputStreamWriter(connection.getOutputStream());
out.flush();
out.close();
is = connection.getInputStream();
rdr = Json.createReader(is);
but when i try in postman it's work,
I've read on stackoverflow but still have errors like that
Someone could help me?
Thank You, a greeting,
Try modifying key variable from
String key ="Authorization : 402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
// to something like below
String key ="402c669e45534f868f5d2dd53c8e345f,a80797e0df9c4696b5494635dae02461";
I have the following code
URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
if(conn.getResponseCode() == 200){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
If I am not interested in the response from the server, can I remove the following code?
if(conn.getResponseCode() == 200){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
Considering that the code, in it's entirety as it is, causes a java.net.ProtocolException, is there a way to still grab the server response and execute conn.getOutputStream();? In what order? What are the consequences of not obtaining the response aside from the obvious reporting concerns?
The problem is that once you get the response code, you have sent your post. In your code, you don't write anything to the output stream before you get the response. So, you are essentially sending nothing over the post (just that header info), getting the response code, and then trying to write to it again, which is not allowed. What you need to do is write to the output stream first, and then get the response code like so:
public static void main(String[] args) throws IOException {
URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
for (char c : input.toCharArray()) {
os.write(c);
}
os.close();
if(conn.getResponseCode() == 200){
System.out.println("Success");
} else {
System.out.println("Time out set for 30 seconds");
}
}
Here's a little tutorial:
Reading and Writing Tutorial
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.