Hello,
Considering URL-1 as http://www.apache.org/ and URL-2 as
http://www.apache.org/foundation/faq.html, below is the piece of code.
It is giving ResponseBody for URL-2 as the that of URL-1.
Am i missing something, please correct me.
Requirement: URL-2 is embeded in the page of URL-1. I need to simulate
the hyper-link(URL-2) clicking in the page of URL-1 using HTTPClient.
Please help,
Thanks in Advance,
Sanjeev Kumar Neemkar
Java Code used as below:
******************************
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method1 = new GetMethod(url); //URL-1
//http://www.apache.org/foundation/faq.html
GetMethod method2 = new GetMethod(url + "foundation/faq.html"); //URL-2
// Provide custom retry handler is necessary
method1.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
// Provide custom retry handler is necessary
method2.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method1);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method1 failed: " + method1.getStatusLine());
}
// Read the response body.
byte[] responseBody1 = method1.getResponseBody();
//Release the connection.
method1.releaseConnection();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary
// data
System.out.println("URL-1::" + new String(responseBody1));
////////////////////URL-2/////////////////////
// Execute the method.
int statusCode2 = client.executeMethod(method2);
if (statusCode2 != HttpStatus.SC_OK) {
System.err.println("Method2 failed: " + method2.getStatusLine());
}
// Read the response body.
byte[] responseBody2 = method1.getResponseBody();
//Release the connection.
method2.releaseConnection();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary
// data
System.out.println("URL-2::" + new String(responseBody2));
} 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.
//method1.releaseConnection();
}
}
}