How to automatically redirect to HttpClient (java, apache)

I create httpClient and set the settings

HttpClient client = new HttpClient();

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

First request (receive)

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;
    }
}

The answer is correct.

Second request (message):

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 answer is also correct, but I need to redirect it to Headers.Location.

I do not know how to get the value from the location of the headers or how to automatically enable redirection.

+5
source share
4 answers

- HttpClient 3.x , POST PUT. POST GET , HttpClient 4.x, .

+6

3.x HttpClient , 301 302, Location :

client.executeMethod(post);
int status = post.getStatusCode();
if (status == 301 || status == 302) {
  String location = post.getResponseHeader("Location").toString();
  URI uri = new URI(location, false);
  post.setURI(uri);
  client.executeMethod(post);
}
+1

:

second.setFollowRedirects(true);
0

, LaxRedirectStrategy

0

All Articles