How to Pass header attributes via java.net.URL - java

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.

Related

how to set HttpsURLConnection method type to POST

I am writing a unit test class in Java, in that I want to set the method type POST, but it is showing me GET while debugging. Below is the code snippet I am trying. ANny help is appreciated.
HttpsURLConnection connection = null;
URL url = new URL("wsURL");
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInputMethod("POST");
You was using connection.setInputMethod("POST");
but you should have used connection.setRequestMethod("POST");
After changing setInputMethod to setRequestMethod("POST") it should work

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

Wait for redirect, read form then post

I made an app that basically just posts a form to login then gets data using an API. Now the website it's for changed the way it works so that when you load the login page it redirects you to one with a random string in the query string and a different random string in the form action.
Since I can't just do an HTTPS POST request to the submit page anymore I need a way to load the login page, wait for the redirect and then wait for load again and then use the form action as HTTPS POST URL.
How do I load a page, specifically wait for it to redirect and then be done loading?
What I'm using now is pretty much this:
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
urlConnection.setConnectTimeout(5000);
String urlParameters = "ctl00$ContentPlaceHolder1$UsernameTextBox="+ URLEncoder.encode(inumber, "UTF-8") + "&ctl00$ContentPlaceHolder1$PasswordTextBox="+ URLEncoder.encode(password, "UTF-8");
urlConnection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(urlParameters);
out.flush();
out.close();
You have a couple of options:
use HTTPURLConnection#setInstanceFollowRedirects(boolean) and ensure that you request the initial page with the same protocol as the redirect (it won't follow otherwise)
use [Google HTTP Client] which supports arbitrary redirects

POST to a HTTPS service

I need to know how to POST to a HTTPS web service. I went through the tutorial but it didn't help because it is too old.
Can anyone please help me out by giving me a good tutorial or some sample code to start with?
Try apache HttpClient library. It supports https.
Something like this:
URL url = new URL("https://...");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
//write the request body
OutputStream requestBody = connection.getOutputStream();
...
requestBody.flush();
//send the request and get the response body
InputStream responseBody = connection.getInputStream();
...

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