该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JOptionPane;
/*
* 模拟登录系统的简单示例
* */
public class Login {
static String sURL = "http://hwid1.vmall.com/oauth2/portal/login.jsp";
static String responseCookie;// 标示Session必须
static String string = "http://hwid1.vmall.com";
// 测试登录功能,返回“自动”登录后的页面
public static String login(String usr, String pwd) throws IOException {
String authcode;
String sTotalString = null;
// 创建URL,
URL url = new URL(sURL);
// 创建URL的URLURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 配置URLConnection
connection.setDoInput(true);
connection.setDoOutput(true);// 允许连接提交信息
connection.setRequestMethod("POST");// 网页默认“GET”提交方式
// 设置登陆的字符串的可变字符序列
StringBuffer sb = new StringBuffer();
sb.append("userAccount=" + usr);
sb.append("&password=" + pwd);
authcode = JOptionPane.showInputDialog("请输入验证码:");
sb.append("&authcode=" + authcode);
connection.setRequestProperty("Content-Length",
String.valueOf(sb.toString().length()));
connection.connect();
// 获取URL的输出流
OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream(),"utf-8");
// 带参数(账号密码验证码)请求网页
os.write(sb.toString());
os.close();
// 取到所用的Cookie
responseCookie = connection.getHeaderField("Set-Cookie");
// 重新请求一个页面
url = new URL(string);
// 调用此 URL 的协议处理程序的 openConnection 方法都打开一个新的连接。
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 允许连接提交信息
// 给服务器送登录后的cookie
connection.setRequestProperty("Cookie", responseCookie);
connection.connect();
// 读取返回的页面信息到br1
BufferedReader br1 = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));
// 输出一个字符
String sTotalStrings = null;
while ((sTotalString = br1.readLine()) != null) {
sTotalStrings = sTotalStrings + sTotalString;
}
br1.close();
return sTotalStrings;
}
}