Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How auto redirect in HttpClient (java, apache)

I create httpClient and set settings

HttpClient client = new HttpClient();

client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setContentCharset("UTF-8");

First request (get)

GetMethod first = new GetMethod("http://vk.com");
int returnCode = client.executeMethod(first);

BufferedReader br = null;
String lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
    System.err.println("The Post method is not implemented by this URI");
    // still consume the response body
    first.getResponseBodyAsString();
} else {
    br = new BufferedReader(new InputStreamReader(first.getResponseBodyAsStream(), Charset.forName("windows-1251")));
    String readLine = "";
    while (((readLine = br.readLine()) != null)) {
        lineResult += readLine;
    }
}

Response correct.

Second request (post):

PostMethod second = new PostMethod("http://login.vk.com/?act=login");

second.setRequestHeader("Referer", "http://vk.com/");

second.addParameter("act", "login");
second.addParameter("al_frame", "1");
second.addParameter("captcha_key", "");
second.addParameter("captcha_sid", "");
second.addParameter("expire", "");
second.addParameter("q", "1");
second.addParameter("from_host", "vk.com");
second.addParameter("email", email);
second.addParameter("pass", password);

returnCode = client.executeMethod(second);

br = null;
lineResult = "";
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
    System.err.println("The Post method is not implemented by this URI");
    // still consume the response body
    second.getResponseBodyAsString();
} else {
    br = new BufferedReader(new InputStreamReader(second.getResponseBodyAsStream()));
    String readLine = "";
    while (((readLine = br.readLine()) != null)) {
        lineResult += readLine;
    }
}

this response is correct too, but I need to be redirected to Headers.Location.

I do not know how to get value from Headers Location or how to automatically enable redirection.

like image 255
Mediator Avatar asked Apr 30 '11 08:04

Mediator


1 Answers

Due to design limitations HttpClient 3.x is unable to automatically handle redirects of entity enclosing requests such as POST and PUT. You either have to manually convert POST request to a GET upon redirect or upgrade to HttpClient 4.x, which can handle all types of redirects automatically.

like image 64
ok2c Avatar answered Oct 01 '22 14:10

ok2c