I use command "curl -X DELETE --header 'Accept: application/json' 'http://10.10.1.29:8181/onos/v1/flows/application/olsrflow' -u karaf:karaf"
It Can work.
but use JAVA Code does't work.
have any problem in my JAVA code?
URL dc0ContrailUrl2 = new URL("http://10.10.1.29:8181/onos/v1/flows/application/olsrflow");
HttpURLConnection dcConn2 = (HttpURLConnection) dc0ContrailUrl2.openConnection();
dcConn2.setDoOutput(true);
String login = "karaf:karaf";
String content = URLEncoder.encode (login) ;
String basicAuth = "Basic " + new String(new Base64().encode(login.getBytes()));
dcConn2.setRequestProperty("Authorization",basicAuth);
dcConn2.setRequestProperty("Content-Type", "application/json");
dcConn2.setRequestMethod("DELETE");
BufferedReader in2 = new BufferedReader(new InputStreamReader(dcConn2.getInputStream()));
String inputLine2;
while ((inputLine2 = in2.readLine()) != null){ //while response is not null, assign response to inputLine and print inputLine
System.out.println(inputLine2);
}
in2.close();
error HTTP response code: 415
You did not add Accept type the same as curl. Add the following line and remove the Content-Type:
dcConn2.setRequestProperty("Accept", "application/json");
Typically it means that server does not support MediaType has been passed. You have to figure out what does it expect and setup it in your request accordingly.
Related
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");
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'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package).
I'm using java.net.HttpURLConnection, here is a small region of my code :
URL obj = new URL(urlPost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT
String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
if (!typeRequest.equals("GET")){
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParam);
wr.flush();
}
}
if (con.getResponseCode() == 200){
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
}
}
I tried sending my PUT parameters the "POST" way and also directly in the URL.
It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.
Thanks for reading, I hope you will be able to give me some hints to debug the problem.
What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
I have to make a request to an api.
The curl that works is:
curl -u apiKey:pass -H "Accept: application/json" https://subdomain.chargify.com/portal/customers/id/management_link.json
and the java code that i have so far is:
String userpass = apiKey + ":" + pass;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
URL url = new URL(stringUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestProperty("Accept", "application/json");
uc.setRequestProperty("Authorization", basicAuth);
InputStream content = uc.getInputStream();
int status = uc.getResponseCode();
BufferedReader in = new BufferedReader (new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
Every time i get a 401 response code.
What am I doing wrong?
Your request requires User Aunthentication. As the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. Check how you are generating and validating key
I am trying to submit a json post request using HttpURLConnection in Scala. I followed along to two tutorials and produced this:
def sendPost(url: String, jsonHash: String) {
val conn: HttpURLConnection = new URL(url).openConnection().asInstanceOf[HttpURLConnection]
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "application/json")
conn.setRequestProperty("Accept", "application/json")
conn.setDoOutput(true)
conn.connect()
val wr = new DataOutputStream(conn.getOutputStream)
wr.writeBytes(jsonHash)
wr.flush()
wr.close()
val responseCode = conn.getResponseCode
println("Sent: " + jsonHash + " to " + url + " received " + responseCode)
val in = new BufferedReader(new InputStreamReader(conn.getInputStream))
var response: String = ""
while(response != null) {
response = in.readLine()
println(response)
}
in.close()
}
It responds with:
Sent: '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"myemail#thecompany.com", "async":false}' to http://localhost:4040/scheduler/iso8601 received 500
java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost:4040/scheduler/iso8601
stemming from
val in = new BufferedReader(new InputStreamReader(conn.getInputStream))
but if I rebuild it as a curl request, it works fine:
curl -X POST -H 'Content-Type: application/json' -d '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"myemail#thecompany.com", "async":false}' http://localhost:4040/scheduler/iso8601
requirement failed: Vertex already exists in graph Scala-Post-Test
(which is what I expect)
Any insight to what is wrong? I'm trying to sniff the packets now to determine what is different.
(Note: I had previously given up on sys.process._)
The issue is here:
Sent: '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"myemail#thecompany.com", "async":false}' to http://localhost:4040/scheduler/iso8601 received 500
You'll note your JSON is surrounded by single quotes. This makes it invalid.
Also worth noting is that while this code works, you are using a DataOutputStream.writeBytes() to output your data. This would be problematic if your string including anything but single-byte characters; it strips the high 8 bits off each char (Java uses 2-byte chars to hold UTF-16 codepoints).
It's better to use something more suited for String output. The same technique you use for input, for example:
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(conn.getOutputStream));
out.write(jsonString);
out.close();