PORT Change in error case: HttpURLConnection - java

I am consuming API using HttpURLConnection in my android application and its running fine but if I get response code except then 200 ok (like 404, 500) my port is changing when I hit next request after error response code:
my code for android request is below and wireshark log as well:
try {
url = new URL(path_url + apiMsg); //in the real code, there is an ip and a port
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","*/*");
}
Please refer wireshark log:
https://files.fm/u/w7umrwwk
So how to avoid PORT change in error scenario as well like in success 200 case, so that we continue to run on the same PORT.

read about sun.net.http.errorstream.enableBuffering in HttpURLConnection source code.
By default when response code is >= 400 then the connection is closed.
It is a clean though not so efficient way of handling error streams.
Instead of setting obscure system properties to handle this, it would be better to move to a proper http client like apache.

Related

HttpUrlConnection Post with header info but no body

I am developing an Android app that uses an API I developed.
I am doing this connection using HttpUrlConnection and so far the login works fine. The problem arises with the logout. It´s not doing anything. When I do the logout request with Postman then it works fine, but with HttpUrlConnection it does not.
The logout works like this:
Do a POST request to http://ipaddress:12345/api/LogOut
and in the header include the token of the logged user. Then the server should go to the database and delete the token for that user:
This is how I´m trying to do the request:
URL url = new URL(getString(R.string.url) + "LogOut");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Token", TokenSingleton.getToken());
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.connect();
con.getOutputStream().flush();
con.getOutputStream().close();
con.disconnect();
Nothing happens until you do some input. At least call getResponseCode() to see whether you got a 200 or not. Preferably you should consume the input stream, if 200 <= response code <= 299, otherwise the error stream.
NB setDoOutput(true) sets the request method to POST. You don't need to do that yourself. And setDoInput(true) is the default. And close() implies flush().

JAVA POST request and then redirect to it?

What I need to do is send POST request to specific URL with two parameters and when the request is sent, I need to redirect user to that link so that he would be able to access functionality.
So far, what I have managed to do from various examples is this:
private void postRemoteAdvisoryLink() throws IOException {
URL obj = new URL(KdrmApplicationContext.getRemoteAdvisoryUrlPath());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(60000);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// For post only - start
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("?auth=ssor&TransportKey=" + ssorTransportKey).getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
}
The problem is that now I get connection time out when trying to execute OutputStream os = con.getOutputStream(); line. Also, I still have no idea how to redirect user when request is completed.
Any ideas?
Using the basic Java URL classes would require you to manually handle the details of HTTP protocol - it's better to use libraries like Apache Http Components, as they deal with the underlying protocols for you. Some examples including POST requests can be found on their website.
Given the original question, the Timeout is likely related to host not responding or your Java application being unable to connect to given URL (due to no proxy configuration for example).
If you want to redirect a request based on the answer, you need to check the response headers and http status - if the status is 302, then there should be a header called Location, which will contain the URL you should make another request to.
Before getting an OutputStream, also make sure to set the Content-Length header (and ideally the Content-Type header as well).

Java Client code to call restful web service

Can anybody tell me how to write a java client code to call restful web service with one parameter say email? I am trying the below code. But I am getting response as Success. Once this is success, I need the below XPHONE value. How to get this value?
XPHONE: 52-33-3669-7000
Here is the client code:
URL url = new URL("http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr=user.email");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Accept",
"application/json");
conn.connect();
I think you just missing response body handling.
There is nice article about rest-client code: article.
You can try using the JavaLite Http client:
JavaLite Http
Depends on how API is implemented value can be in response body or even in header, so this info you should know from specification or ask in dev team.
First try to check if everything works fine using CURL or better "Advanced rest client" ( its extension in Chrome browser) if it works, than just transfer flow to your code. How to use advanced rest client look here

IHS (Apache) 400 Error when adding UUID header to HttpUrlConnection

I need to add a header ("correlationIdHeader") to a GET Request using Java's HttpUrlConnection. However the server (IBM Http Server - built on Apache) answers with a 400 Error and the following info:
Request header field is missing ':' separator
My code:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("correlationIdHeader", UUID.randomUUID().toString());
conn.setRequestMethod(HttpMethod.GET.name());
conn.setRequestProperty("Accept", contentType);
int responseCode= conn.getResponseCode();
Any idea what could be happening here?
EDIT: it has to do with UUID.randomUUID().toString(). I don't know why but it doesn't like UUID's format. Why?

How to open many HttpURLConnection?

I'm trying to implement a simple URL availability checker which basically checks if the link is available (No HTTP 403, 404 etc. returned).
I have more than 20,000 links(to different servers/websites) in my database for testing purposes but it doesn't seems to work when I try to create more than 10 Threads.
Here is the code I'm using for opening the connection and reading response code within each WorkerThread.
URL url = new URL(dto.getUrl());
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
// httpUrlConnection.setConnectTimeout(6000);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(false);
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.setRequestProperty("Host", dto.getUrl().replace("http://", ""));
// httpUrlConnection.setRequestProperty("Connection",
// "Keep-Alive");
httpUrlConnection.setRequestProperty("User-Agent", USER_AGENT);
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.connect();
int code = httpUrlConnection.getResponseCode();
Few issues I have noticed when having multiple threads opening the connections:
1) Only first 100-200 connections seems to open with no problem, after that, I start getting "Read timeout", "Connection timeout", "Connection reset" etc. Although, if you try to run the code again the links which have thrown above exceptions will return proper response code (if they get processed in first 100).
2) The response code sometimes is not valid (especially if the link was processed after first 100 links). I have noticed that sometimes 404 is returned when in fact it should return 200 (I checked it by putting link in first 100).
I did try using Apache's Http client but it also fails to process links correctly with many threads.
So does anyone know a solution to this problem ? What is the maximum amount of connections you could open using HttpURLConnection using multiple threads ? Is there any other way to open many HTTP connections and check response codes ?
Thank you all in advance !

Categories

Resources