package com.haojiahong.test; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; public class KaixinLoginTest { // The HttpClient is used in one session private static HttpResponse response; private static DefaultHttpClient httpclient = new DefaultHttpClient(); public static void main(String[] args) throws Exception { KaixinLoginTest kaixin = new KaixinLoginTest(); kaixin.printText(); } // 原因就是在这里,一开始使用post提交url,可是这个url这是一个类似jsp的地址,给它参数后他并不走后台业务逻辑判断, // 因此也就不会返回给你正确的跳转地址,即使你测试得到了正确的statusCode // 所以一定要是用请求后台acting的地址,actionUrl,这个可以去对应的网页源码中查到。 private static String url = "http://www.kaixin001.com/login/login.php"; private static String actionUrl = "https://security.kaixin001.com/login/login_post.php"; private boolean login() { HttpPost httpost = new HttpPost(actionUrl); BasicNameValuePair username = new BasicNameValuePair("email", "**********你的账号*******"); BasicNameValuePair password = new BasicNameValuePair("password", "**********你的密码*******"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(username); nvps.add(password); try { httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); //302表示临时跳转地址。 System.out.println(response.getStatusLine().getStatusCode() + "++++++++++++++++++++++++++++++++++++++++++++"); } catch (Exception e) { e.printStackTrace(); return false; } finally { httpost.abort(); } return true; } private String getRedirectLocation() { //跳转成功后,这里会收到一个完整的url地址,而不是类似于"/home/"这样的地址。 String location = response.getFirstHeader("Location").getValue(); if (location == null) { return null; } return location; } private String getText(String redirectLocation) { HttpGet httpget = new HttpGet(redirectLocation); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = ""; try { //打印出来跳转成功后的页面源码。 responseBody = httpclient.execute(httpget, responseHandler); } catch (Exception e) { e.printStackTrace(); responseBody = null; } finally { httpget.abort(); httpclient.getConnectionManager().shutdown(); } return responseBody; } public void printText() { if (login()) { String redirectLocation = getRedirectLocation(); if (redirectLocation != null) { System.out.println(getText(redirectLocation)); } } } }//有些网站会对参数进行加密,action请求地址也写的不明确,比如博客园网站,还没有学会改怎么去模拟登陆,欢迎大神指教。
时间: 2024-10-10 18:37:02