- 1 import java.io.IOException;
- 2 import java.util.List;
- 3 import java.io.BufferedReader;
- 4 import java.io.IOException;
- 5 import java.io.InputStreamReader;
- 6 import java.io.PrintWriter;
- 7 import java.net.URL;
- 8 import java.net.URLConnection;
- 9 10 public class myLoginAction {
- 11 12
- /**
- 13 * 查询是否用户已注册
- 14 * @return
- 15 * @throws Exception
- 16 */
- 17 public void checkUser() throws Exception {
- 18 Loginer loginer = (Loginer) request.getSession() 19.getAttribute("loginer");
- 20 21 String url = "http://www.youtest.com/login.php"; //远程系统登录action地址
- 22 String param = "username=Tom&password=123456"; //参数
- 23 String temp = "alert('用户名或密码错误');"; //返回的信息,此处是错误信息,用于比较。 视情况而定
- 24 boolean result = false;
- 25 //验证数据是否能登录
- 26 result = sendPost(url, param, temp);
- 27
- if (result) {
- 28
- return "login";
- 29
- } else {
- 30
- return "register";
- 31
- }
- 32
- }
- 33 34 //访问远程登录action并获取返回的信息
- 35 public static boolean sendPost(String url, String param, String temp) {
- 36 PrintWriter out = null;
- 37 BufferedReader in =null;
- 38 boolean result = true;
- 39
- try {
- 40 URL realUrl = new URL(url);
- 41 // 打开和URL之间的连接
- 42 URLConnection conn = realUrl.openConnection();
- 43 // 设置通用的请求属性
- 44 conn.setRequestProperty("accept", "*/*");
- 45 conn.setRequestProperty("connection", "Keep-Alive");
- 46 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- 47 // 发送POST请求必须设置如下两行
- 48 conn.setDoOutput(true);
- 49 conn.setDoInput(true);
- 50 // 获取URLConnection对象对应的输出流
- 51 out = new PrintWriter(conn.getOutputStream());
- 52 // 发送请求参数
- 53 out.print(param);
- 54 // flush输出流的缓冲
- 55 out.flush();
- 56 // 定义BufferedReader输入流来读取URL的响应
- 57 in =new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
- 58 String line;
- 59
- while ((line = in.readLine()) != null) {
- 60
- if (temp.equals((line.trim()))) {
- 61 System.out.println("错误的line:" + line);
- 62 result = false;
- 63
- }
- 64
- }
- 65
- } catch(Exception e) {
- 66 result = false;
- 67 logger.error("发送 POST 请求出现异常!" + e);
- 68 System.out.println("发送 POST 请求出现异常!" + e);
- 69 e.printStackTrace();
- 70
- } finally {
- 71
- try {
- 72
- if (out != null) {
- 73 out.close();
- 74
- }
- 75
- if ( in !=null) {
- 76 in .close();
- 77
- }
- 78
- } catch(IOException ex) {
- 79 logger.error(ex);
- 80 ex.printStackTrace();
- 81
- }
- 82
- }
- 83
- return result;
- 84
- }
- 85
- }
来源: