Hi
using apache HttpClinet i have to connect to two different URLs based on conditions.
we have given two urls URL1 and URl2.
initially i have to connect to URL1 .if it fails due to communication errors retry for 3 times,then also it failed Now connect to URL2 and repeat the same process.finally if URL2 also fails.read from database.
here is my code.
how can i achieve it.please help me.
package one; import org.apache.commons.httpclient.; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.; import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class MyHttpClient {
private static String url = "https://URL1"; private static String url2 = "https://URL2";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
HttpClient client2= new HttpClient();
// Create a method instance.
PostMethod method = new PostMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
PostMethod method2 = new PostMethod(url2);
// Provide custom retry handler is necessary
method2.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
if (statusCode == HttpStatus.SC_OK) {
switch (statusCode) {
case 200: // HTTP_OK
{
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
}
case 504: //HTTP_GATEWAY_TIMEOUT
{
//connection = _sendPending();
break;
}
default: //OTHER HTTP_SERVER ERRORS
{
System.out.println ("Invalid code:"+statusCode);
break;
}
}//switch
}
int statusCode2 = client2.executeMethod(method2);
if (statusCode2 != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method2.getStatusLine());
}
switch (statusCode2) {
case 200: // HTTP_OK
{
// Read the response body.
byte[] responseBody2 = method2.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody2));
}
case 504: //HTTP_GATEWAY_TIMEOUT
{
//connection = _sendPending();
break;
}
default: //OTHER HTTP_SERVER ERRORS
{
System.out.println ("Invalid code2:"+statusCode2);
break;
}
}
System.out.println(".........");
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
} }