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");
Related
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.
I have this code:
HttpURLConnection connection = (HttpURLConnection)(new URL(url)).openConnection();
connection.setRequestMethod("GET");
What I want is just to send a request to url.
I don't care about response.
I just need to send request.
How I do that?
You try can with post method instead of get method
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.
I'm trying to post some login data to a form in order to grab the cookies from the response.
The url is: https://www.deviantart.com/users/login
However I can not get the server to return FOUND 302 but only 200, so I think I'm b0rking my querystring or headers in some manner:
try {
String query = URLEncoder.encode("&username="+user+"&password="+password+"&remember_me=1", "UTF-8");
URL url = new URL("https://www.deviantart.com/users/login");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
HttpsURLConnection.setFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.deviantart.com");
conn.setRequestProperty("User-Agent", "Mozilla 4.0");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(query.length()));
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
PrintWriter out = new PrintWriter(conn.getOutputStream(), false);
out.write(query);
out.flush();
As far as I know, its normal to get response "200", means that your request was recognized and properly answered.
But when I need to know about HTTP code responses and some details I usually use this link: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
Hope it helps...
A 302 response is a redirect ... telling the browser to go to another page. A sites login page will often do this to send the user to a "login succeeded" page, or back to the home page or the page that the user was originally looking at. But it doesn't have to.
A 200 response means "Succeeded", and for a POST request will result in the browser staying at the login page.
I'd not worry about getting a 200 instead of a 302. If you are sending requests from a Java app, you probably don't care where the site redirects you after login. The thing that matters is whether your credentials have been accepted, and you can only determine that by trying a request that needs authentication. (You need to make sure that your code captures the cookies set by the response to your login POST. They need to be supplied in follow-on requests.)
If you are worried that you have "borked" the login URL query String, fetch the login page and look at its source to see if there are any hidden inputs in the form.
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.