import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class RrLogin {
static final String LOGON_SITE = "http://www.renren.com";
static final int LOGON_PORT = 80;
public Cookie[] login(String name, String pas) {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
PostMethod post = new PostMethod("http://passport.renren.com/PLogin.do");
NameValuePair username = new NameValuePair("email", name);
NameValuePair password = new NameValuePair("password", pas);
NameValuePair origURL = new NameValuePair("origURL",
"http://home.renren.com/Home.do");
NameValuePair domain = new NameValuePair("domain", "renren.com");
NameValuePair formName = new NameValuePair("formName", "");
NameValuePair method = new NameValuePair("method", "");
post.setRequestBody(new NameValuePair[] { username, password, origURL,
domain, formName, method });
try {
client.executeMethod(post);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseString = null;
try {
responseString = new String(post.getResponseBodyAsString()
.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Cookie[] cookies = client.getState().getCookies();
client.getState().addCookies(cookies);
post.releaseConnection();
// 截取转跳地址
if (responseString.lastIndexOf("The URL has moved") > -1) {
responseString.substring(26, responseString.length() - 10);
String newUrl = responseString.substring(27, responseString
.length() - 11);
// 实施转跳
GetMethod get = new GetMethod(newUrl);
get.setRequestHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;)");
get.setRequestHeader("Cookie", cookies.toString());
try {
client.executeMethod(get);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
get.releaseConnection();
return client.getState().getCookies();
}
return null;
}
|