Kristina
Kristina

Reputation: 11

Using HttpPost in Java to log in?

I was looking for a solution to my problem all around but couldn't really find the exact one.

I try to access to website which first requires to login. I try to login using HttpPost in Java but the response is empty and the next HttpGet returns redirection link to login page. Instead of the empty response I should expect to receive the redirection link to some internal page as while using a browser, right?

I'm new to the protocols, connections etc and I will really appreciate some ideas about what can be wrong.

HttpPost authpost = new HttpPost("/login/");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("submit", "ok"));
formparams.add(new BasicNameValuePair("username", ske_username));
formparams.add(new BasicNameValuePair("password", ske_password));

try {
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
    authpost.setEntity(formEntity);
    HttpResponse response = client.execute(targetHost, authpost);
    HttpEntity entity = response.getEntity();

    System.out.println(EntityUtils.toString(entity));

} catch (IOException ex) {
...

Upvotes: 1

Views: 834

Answers (3)

Eli Acherkan
Eli Acherkan

Reputation: 6411

IMHO your next step should be understanding better how authentication on that site works, at the request-response level. You can use a network sniffer (such as Fiddler or Wireshark) and perform the login manually (from a browser). The sniffer will show you the full contents of the requests and the responses, and then you'll know what your code should be looking for. (Like RHSeeger, I suspect that the answer lies in HTTP headers, especially cookies.)

Upvotes: 1

Mobile Developer
Mobile Developer

Reputation: 5760

if you set follow redirects of your connection to true:

conn.setInstanceFollowRedirects(true);

then you will be automatically redirected and as the response you et the final page. If not, it means something is wrong with implementation of your connection. Maybe something is missign. Check what exactly you get in response (response code and header)

Upvotes: 0

RHSeeger
RHSeeger

Reputation: 16262

Are you checking the response to see if it returns cookies that you need to have set in your subsequent communications?

Upvotes: 1

Related Questions