connection.setRequestProperty and excplicitly writing to the urloutputstream are they same? - java

URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
Is
connection.setRequestProperty(key, value);
the same as
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("key=" + value);
writer.close();
?
If not, please correct me.

No, it is not. The URLConnection#setRequestProperty() sets a request header. For HTTP requests you can find all possible headers here.
The writer just writes the request body. In case of POST with urlencoded content, you'd normally write the query string into the request body instead of appending it to the request URI like as in GET.
That said, connection.setDoOutput(true); already implicitly sets the request method to POST in case of a HTTP URI (because it's implicitly required to write to the request body then), so doing an connection.setRequestMethod("POST"); afterwards is unnecessary.

Related

Send Post request to endpoint but ignore response

I am writing a java method to fire a post request to one of our endpoints.
All the method needs to worry about is sending the request, but not being concerned if the endpoint has received it (fire and forget).
How would I achieve this with HttpUrlConnection?
I have the following but i'm unsure if firing connection.disconnect(); is best practice?
HttpURLConnection connection = (HttpURLConnection) EndpointUrl.openConnection();
// Set the http rest call to POST.
connection.setRequestMethod("POST");
// Set the request properties, including the Authorization tag.
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", header);
connection.setDoOutput(true);
ObjectMapper mapper = new ObjectMapper();
try(OutputStream outputStream = connection.getOutputStream()) {
byte[] input = mapper.writeValueAsBytes(log);
outputStream.write(input, 0, input.length);
}
connection.disconnect();
From docs.oracle.com:
disconnect()
Indicates that other requests to the server are unlikely in the near future.
For the sake of simply sending a message to the client and then disconnecting, I think this is the safest practice. Note that calling disconnect() should not imply that the HttpURLConnection instance can be reused for new connections.

HTTP Delete Request on a tomcat server

I'm trying to delete a class given its id number from a tomcat server. I did some research on DELETE request where some sources were saying it's similar to the POST request. So, I changed my code accordingly, however I still get an error code 404.
My controller has a delete mapping with #DeleteMapping("/classes/{cId}") and here's my code to delete a class based on its id number.
URL url = new URL("http://localhost:8080/classes/{cId}");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStreamWriter wr = new
OutputStreamWriter(connection.getOutputStream());
wr.write("{\"cId\":" + cId + "}");
wr.flush();
wr.close();
connection.connect();
connection.disconnect();
Can someone tell me what I'm doing wrong here? How would I change my code to successfully delete a class?

How to Pass header attributes via java.net.URL

I am using a third party API in my program who's job is to construct a SOAP message by using the java.net.URL object passed as an input. I am constructing the URL object by passing the url as a String and thats it.
The requirement now is to attach a header to the URL before passing it to the third party API. My challenge is the API takes only URL as an input and nothing else. AS i have exhausted all my options, can you please let me know if there is any workaround or options available that can be applied in this scenario?
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod(method.toUpperCase());
connection.setRequestProperty("Authorization", "BASIC "+new String(encodedBase64));
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
This is how I did it with my URL object
setRequestProperty will add Key-Value pair to the Header of the Request.

HttpUrlConnection method is always GET on android

URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//connection.setRequestMethod("POST") <- this didn't help either
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("string=test");
out.close();
connection.close()
The code above WORKS on desktop JVM, sends a post request, parsed on server-side successfully with response 200, however on android, the request method stays GET (yes I checked it IS false) and results in a 404 exception. Official docs say that setting doOutput to true triggers setting the request method to POST but that doesn't seem the case.
404 is not an exception. It is a HTTP status code returned by the server you make the request to and it means that the url you make the request to is not found. That has nothing to do with POST being set or not.
Things to check:
If the url you are making a request to is right.
If the server has a POST controller/handler mapped to the url you are making the request to.
Ask the guy who develops the server if he is handling the cases right ans if he's sending the correct response codes for the relevant scenarios.
Extra info: if the url is registered on the service but a POST request is not allowed you would get a 415 response code.
When posting data to a server, I'm setting some additional request header:
String query = "string=test";
URL url = new URL("http://myserver.com/myendpoint");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
connection.setFixedLengthStreamingMode(query.getBytes("UTF-8").length);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(query);
But as suggested, the 404 exception usually means, that the endpoint, you're trying to access, isn't available.
Try it:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");

Why do I need getInputStream for HttpUrlConnection to send request?

I have some code that sends a POST request to a PHP script from a Java applet:
String message = URLEncoder.encode(s, "UTF-8");
URL url = new URL(getCodeBase(), "script.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("message=" + message);
out.close();
But this doesn't work in sending the request. I have to add code that calls getInputStream() and reads all of the input for this to work. Why is this? What do I do if I only want to only send a request and not receive one?
You don't, but you do have to call either getInputStream() or getResponseCode(). Otherwise nothing is sent, but also otherwise you don't have any way of knowing whether the call succeeded or not.

Categories