Why do I need getInputStream for HttpUrlConnection to send request? - java

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.

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.

How to use HttpURLConnection to send request without handling response in 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

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");

Calling an web service from java program

I am trying to call an web service by sending an xml file as input and i should be receiving an xml as a reply but whenever i send the xml i get proxy authentication error so i thought i was sending the wrong xml but the same xml works fine when i use SOAP UI so i guess there is some problem with my code.
Here is the code below
URL url = null;
String strUrl="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope\" xmlns:soap=\"SoapAuthenticator\" xmlns:ship=\"http://ws.consignorsupport.no/ShipAdvisor\"><soapenv:Header> <soap:ServiceAuthenticationHeader><soap:Username>TDC43671</soap:Username> <soap:Password>hTiNMft/KaMfDDD</soap:Password><soap:IsEncrypted>false</soap:IsEncrypted></soap:ServiceAuthenticationHeader></soapenv:Header><soapenv:Body><ship:SearchForDropPoints><ship:productConceptID>92</ship:productConceptID><ship:installationID>00000000018</ship:installationID><ship:country>DK</ship:country><ship:address></ship:address><ship:postCode>6000</ship:postCode><ship:city></ship:city><ship:limit>5</ship:limit></ship:SearchForDropPoints></soapenv:Body></soapenv:Envelope>";
String ss="http://www.consignorsupport.no/ShipAdvisor/Main.asmx";
url = new URL(ss);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-type", "text/xml");
conn.setRequestProperty("Accept", "text/xml, application/xml");
conn.setRequestMethod("POST");
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(strUrl);
wr.flush();
wr.close();
int iHttpResponseCode = conn.getResponseCode();
String strErrorMessage = conn.getResponseMessage();
System.out.println("Getting Response status");
System.out.println(iHttpResponseCode);
System.out.println(strErrorMessage);
Can anybode help me as to where i am going wrong.
If you get a proxyauthentication error, chances are that that really is the issue. Maybe soap ui is set up with the correct proxy info? Or gets it from the system settings? Your java code won't automatically pick up on these settings. Check if you have a system proxy configured, or one in soapUI.

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

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.

Categories