Reputation: 809
There is a webservice on some other server which I am calling in my Java Code. It responses only for POST method (there is NO GET method) available. This request / response works correctly while I implement the full method with request XML and call the Webservice, i.e. it works correctly.
But requirement is --> there will be three webservice URLs (configurable from my Application by Admin User). First, I have to check whether the first URL one is connection or not. If Not connecting, then go for second connection...then 3rd one.
I am using the below code , but again and again it is giving me
{responseCode = 500}. and not {responseCode = 200}.
Kindly Suggest me how can I check the connection is established or not ?
/* Start : Surajit Biswas (25-NOV-2015) : test if Alcatel WS is connection or not*/
String wsURL = "https://hostservername:postnumber";
String wsUserName = "someUserName";
String wsPassword = "somePassword";
String requestXML = "<soapenv:Envelope ...."; /* As I told, not required here*/
try{
String authString = wsUserName+":"+wsPassword;
byte[] byteAuthStr = authString.getBytes();
String authBase64Str = Base64.encode(byteAuthStr);
System.out.println(authBase64Str);
URL url = new URL(wsURL);
URLConnection conn = url.openConnection();
HttpURLConnection connection = (HttpURLConnection)conn;
connection.setDoOutput(true);
/*connection.setRequestMethod("GET");
connection.setRequestMethod("POST");*/ connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Authorization", "Basic "+authBase64Str);
connection.connect();
System.out.println( connection.getResponseCode());
boolean connected = false;
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
System.out.println(url + " **OK**");
connected = true;
break; // fine, go on
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
System.out.println(url + " **gateway timeout**");
break;// retry
case HttpURLConnection.HTTP_UNAVAILABLE:
System.out.println(url + "**unavailable**");
break;// retry, server is unstable
default:
System.out.println(url + " **unknown response code**.");
break ; // abort
}
}catch(Exception ex){
System.err.println("Error creating HTTP connection");
System.out.println(ex.getMessage());
}
}
/* End : Surajit Biswas (25-NOV-2015) : test if Alcatel WS is connection or not*/
Thanks in advance for your help... Surajit Biswas
Upvotes: 1
Views: 2783
Reputation: 90
You can check with this line
URLConnection conn = url.openConnection();
if(conn != null)
{
//do your stuff
}
else //call other url
Upvotes: -1
Reputation: 311039
The way to implement your requirement is simply to try to post to each URL in turn and stop as soon as you get a success.
What you're attempting here is tantamount to trying to predict the future. It won't work. It can't work.
Upvotes: 3