package yaxing.qw.inter.impl;import java.io.*;
import java.net.*;public class LoginUtil {
// 用户登录
@SuppressWarnings("finally")
public String login(String strUrl, String username, String password) {
StringBuffer sb = new StringBuffer("");
try {
// 替换公用部分
strUrl = new LoginUtil().replaceStr(strUrl, "{USERNAME}", username);
strUrl = new LoginUtil().replaceStr(strUrl, "{PASSWORD}", password);
// ==========
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
reader.close();
// 取得cookie
for (int i = 0;; i++) {
String headerName = conn.getHeaderFieldKey(i);
String headerValue = conn.getHeaderField(i);
// test
System.out.println(headerName + ": " + headerValue);
if (headerName != null
&& headerName.equalsIgnoreCase("set-cookie")) {
int j = headerValue.indexOf(";");
sb.append(headerValue.substring(0, j) + ";");
}
if (headerName == null && headerValue == null) {
break;
}
}
// =========
} catch (MalformedURLException e) {
System.out.println("连接URL失败: " + strUrl);
} catch (IOException e) {
System.out.println("输入输出数据流失败: " + strUrl);
} finally {
return sb.toString();
}
} public String replaceStr(String strUrl, String oldStr, String newStr) {
String str = strUrl.substring(0, strUrl.indexOf(oldStr));
str += newStr;
str += strUrl.substring(strUrl.indexOf(oldStr) + oldStr.length());
return str;
} // 测试登陆是否成功
public static void main(String args[]) {
String cookie = new LoginUtil()
.login(
"http://my.58.com/login.aspx?path=http%3a%2f%2fwh.58.com%2f&__VIEWSTATE=%2FwEPDwUJNTY0NjM2MDY2D2QWAgIBD2QWAgIBD2QWAmYPZBYEAgIPFgIeB1Zpc2libGVoZAIDDxYCHwBoZGQrj%2Br%2FtvZ7O0vuaT7OzShePauM0w%3D%3D&__EVENTVALIDATION=%2FwEWAwKU7pKmCgKEyf6dCAL8ityVDf2PKVlaBl7BWKf2qn07nUkQCmiw&skinContainer_Template%24username={USERNAME}&skinContainer_Template%24userpwd={PASSWORD}&checkbox=on&loginSubmit=%E7%99%BB%E5%BD%95",
"vicky530", "qw00000000");
System.out.println(cookie);
}
}前面的代码通过GET方式提交之后,本来应该从报头域中取set-cookie的值组成cookie,但是这里取不到相应的值,导致不能登陆成功。所以也就不能进行下面的一系列操作。希望高手能够给予指点,告诉我原因,谢谢了!!!!!

解决方案 »

  1.   

    自己写太费劲,用HttpClient吧。
      

  2.   

    你的cookie获取的均为空还是报错?
      

  3.   

    首先你要确定你的用户登陆信息放入cookie中
    上面我只看到你取得cookie 的代码
      

  4.   

    我这里是登录58网,在登录的时候用第三方软件可以截取到cookie,本地也会生成cookie。cookies肯定是有的,就是不知道cookies不放在头文件里,还能放在哪里