public static HttpResponse sendGetForSecureDocument(String serverURI, HttpGet request, String login, String password, HttpClient httpClient)
throws IOException, InvalidCredentialsException {
// Step (1): Request the protected resource
if (DEBUG) System.out.println(">> GET(1) "+request.getURI());
HttpResponse documentResponse = httpClient.execute(request);
if (DEBUG) {
System.out.println(">> Response Headers:");
HttpUtils.printResponseHeaders(documentResponse);
}
if (documentResponse.getStatusLine().getStatusCode() == 200) {
Header header = documentResponse.getFirstHeader(AUTHREQUIRED);
if ((header!=null) && ("authrequired".equals(header.getValue()))) {
documentResponse.getEntity().consumeContent();
// The server requires an authentication: Create the login form
HttpPost formPost = new HttpPost(serverURI+"/j_security_check");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("j_username", login));
nvps.add(new BasicNameValuePair("j_password", password));
formPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// Step (2): The client submits the login form
if (DEBUG) System.out.println(">> POST "+formPost.getURI());
HttpResponse formResponse = httpClient.execute(formPost);
if (DEBUG) HttpUtils.printResponseHeaders(formResponse);
header = formResponse.getFirstHeader(AUTHREQUIRED);
if ((header!=null) && ("authfailed".equals(header.getValue()))) {
System.out.println("");
// The login failed
throw new InvalidCredentialsException("Authentication failed");
} else {
System.out.println("False");
formResponse.getEntity().consumeContent();
// The login succeed
// Step (3): Request again the protected resource
if (DEBUG) System.out.println(">> GET(2) "+request.getURI());
HttpGet documentGet2;
try {
documentGet2 = (HttpGet)(request.clone());
return httpClient.execute(documentGet2);
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return documentResponse;
}