Java模拟HTTP登录

 http://zhoujingxian.iteye.com/blog/439738

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

你可能感兴趣的:(java)