[关闭]
@HUST-SuWB 2015-12-22T03:02:22.000000Z 字数 1596 阅读 387

Java模拟登陆(转载)

项目实战


  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. public class TestPost {
  9. public static void testPost() throws IOException {
  10. //连接地址
  11. String surl = "http://219.238.180.***:80/.../loginservlet?command=login";
  12. /**
  13. * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using
  14. * java.net.URL and //java.net.URLConnection
  15. */
  16. URL url = new URL(surl);
  17. URLConnection connection = url.openConnection();
  18. /**
  19. * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
  20. * 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
  21. */
  22. connection.setDoOutput(true);
  23. /**
  24. * 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
  25. */
  26. OutputStreamWriter out = new OutputStreamWriter(connection
  27. .getOutputStream(), "UTF-8");
  28. out.write("user_account=admin&user_password=******"); //post的关键所在!
  29. // remember to clean up
  30. out.flush();
  31. out.close();
  32. /**
  33. * 这样就可以发送一个看起来象这样的POST:
  34. * POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:
  35. * text/plain Content-type: application/x-www-form-urlencoded
  36. * Content-length: 99 username=bob password=someword
  37. */
  38. // 一旦发送成功,用以下方法就可以得到服务器的回应:
  39. String sCurrentLine;
  40. String sTotalString;
  41. sCurrentLine = "";
  42. sTotalString = "";
  43. InputStream l_urlStream;
  44. l_urlStream = connection.getInputStream();
  45. // 传说中的三层包装阿!
  46. BufferedReader l_reader = new BufferedReader(new InputStreamReader(
  47. l_urlStream));
  48. while ((sCurrentLine = l_reader.readLine()) != null) {
  49. sTotalString += sCurrentLine + "\r\n";
  50. }
  51. System.out.println(sTotalString);
  52. }
  53. public static void main(String[] args) throws IOException {
  54. testPost();
  55. }
  56. }

以上代码通过测试,能得到登录后的页面静态代码
有兴趣可以自己测试,注意地址是提交的地址,参数也得一致

原文地址:http://zhoujingxian.iteye.com/blog/439738

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注