日期:2014-05-20 浏览次数:20711 次
public class HttpClientUtil {
private String userName = "";
private String password = "";
String tmpcookies = "";
private static String redirectURL = "http://i.taobao.com/my_taobao.htm";
private static String loginURL = "https://login.taobao.com/member/login.jhtml";
private HttpResponse response;
private DefaultHttpClient httpclient = null;
private String redirectLocation = null;
private String defaultContent = null;
public HttpClientUtil(String userName, String password) {
this.userName = userName;
this.password = password;
}
public void printInfo(String info){
System.out.println(info);
}
public void printError(String info){
System.out.println(info);
}
@SuppressWarnings("deprecation")
public boolean login() {
printInfo("开始登陆。。。");
if (httpclient != null) {
System.out.println("已经登陆成功");
return true;
}
httpclient = null;
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(loginURL);
// All the parameters post to the web site
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("origURL", redirectURL));
nvps.add(new BasicNameValuePair("autoLogin", "true"));
nvps.add(new BasicNameValuePair("TPL_username", userName));
nvps.add(new BasicNameValuePair("TPL_password", password));
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
} catch (Exception e) {
printError("登录失败");
e.printStackTrace();
return false;
} finally {
httpost.abort();
}
Header[] hs = response.getAllHeaders();
for (Header h : hs) {
// System.out.println(h.getName() + ":" + h.getValue());
printInfo(h.getName() + ":" + h.getValue());
}
redirectLocation = getRedirectLocation();
redirectLocation = "http://i.taobao.com/my_taobao.htm";
if (getToken() == null) {
System.out.println("登录失败");
return false;
}
List<org.apache.http.cookie.Cookie> cookies = httpclient
.getCookieStore().getCookies();// 取出登陆成功后,服务器返回的cookies信息,里面保存了服务器端给的“临时证”
tmpcookies = "";
for (int i = 0; i < cookies.size(); i++) {
org.apache.http.cookie.Cookie c = cookies.get(i);
tmpcookies = tmpcookies + c.getName() + "=" + c.getValue() + ";";
// System.out.println(c);
}
printInfo("完成登陆");
return true;
}
private String getRedirectLocation() {
Header locationHeader = response.getFirstHeader("Location");