How to use HttpURLConnection to send request without handling response in Java - java

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

Related

How to read Network Response (PAYLOAD) from GET API call using Java

I want to read the Network Response after API GET call using
URL obj = new URL("https://URLGoesHere");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
Refer attached image to understand what actually I want to read in Response
after API GET call.

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.

android HTTP POST fail

I'm trying to connect and post to a simple java webservice, running the post's URL from chrome succeeded, but android code skip the following lines (without throwing errors), but the webservice doesn't accept the post
HttpPost post = new HttpPost(setFacebookEventsAddress+userId+"/"+accesstoken);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
the webservice method signature handling the above request:
#GET
#Path("setData/{user_id}/{accessToken}")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public String setData(#PathParam("user_id") String user_id,
#PathParam("accessToken") String accessToken) {
since I manage to post throw my browser, anyone can help with what's wrong with my android code?
URL url = new URL(setFacebookEventsAddress+userId+"/"+accesstoken);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ja = readStream(con.getInputStream());
Using HttpURLConnection instead of HttpPost did the trick for me, thanks for all the helpers!
It is not possible to say with any certainty (given the evidence), but my guess would be that the expression
setFacebookEventsAddress + userId + "/" + accesstoken
is evaluating to a different URL to the one you are using from the web browser.
I suggest that you try the following:
Turn on request logging on your server, and compare the URLs in the requests being sent.
Modify your client to print out the response status code and the response body. The latter is likely to be an error page that will give you more clues.
Another possible problem is that your code doesn't appear to be sending any body with the POST request.
On revisiting this, the problem was that you were using / trying to do a POST to a web service that you had configured to support GET only. I expect that if you had looked at the status code you would have found that the response code was "Method not supported".

Does HttpsURLConnection.getInputStream() makes automatic retries?

I am making a service request to a server using HttpsURLConnection like the code below :
URL url = new URL("service/url");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setConnectionTimeout(300000);
connection.setReadTimeout(300000);
parse (connection.getInputStream());
Service sometimes may take longer time, so ideally I should expect a TimeOut Exception but instead the client is making a retry and sending the same request again. Is there a way to explicitly disable any kind of retries? And I am not even sure if the set timeout methods are making any difference.
I am using Java 1.6
UPDATE
I tried connect() and getResponseCode() instead of getInputStream() but same behaviour:
URL url = new URL("service/url");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setConnectionTimeout(300000);
connection.setReadTimeout(300000);
connection.connect();
connection.getResponseCode();
even this is making 2 requests.
UPDATE
HttpClient fixed the issue. In HttpClient you can explicitly set retry to false
You shouldn't be calling openConnection() and connect(), just call openConnection().

Categories