JAVA程序通过后台登陆网站,获取Session,然后再POST Http Request添加数据到数据库的实例

来源:互联网 发布:查看手机端口号 编辑:程序博客网 时间:2024/05/03 03:16
关键字: java http session http request 后台登陆网站

 * 1,在HTTP的WEB应用中, 应用客户端和服务器之间的状态是通过Session来维持的, 而Session的本质就是Cookie,
 * 简单的讲,当浏览器向服务器发送Http请求的时候, HTTP服务器会产生一个SessionID,这个SessionID就唯一的标识了一个客户端到服务器的请求会话过程.
 * 就如同一次会议开始时,主办方给每位到场的嘉宾一个临时的编号胸牌一样, 可以通过这个编号记录每个嘉宾(客户端)的活动(请求状态).
 * 为了保持这个状态, 当服务端向客户端回应的时候,会附带Cookie信息,当然,Cookie里面就包含了SessionID
 * 客户端在执行一系列操作时向服务端发送请求时,也会带上这个SessionID, 一般来说,Session也是一个URL QueryParameter ,就是说,session可以以Key-Value的形式通过URL传递
 * 比如,http://www.51etest.com/dede/login.php?PHPSESSIONID=7dg3dsf19SDf73wqc32fdsf
 * 一般而言,浏览器会自动把此Session信息放入Header报文体中进行传递.
 * 如果浏览器不支持Cookie,那么,浏览器会自动把SessionID附加到URL中去.
 *
 * 2,在这个例子中,以登陆这个功能点进行讲解.
 * 首先,我们登陆的页面是http://www.51etest.com/dede, 我们第一次访问这个页面后,可以从服务器过来的Http Response报文中的Header中找出服务器与浏览器向关联的数据 -- Cookie,
 * 而且Session的值也在Cookie中. 于是,我们可以通过分析Set-Cookie这个Header中的参数的值,找到Seesion的Key-Value段.
 * 然后,我们再向服务器发送请求,请求URL为:post@@http://www.51etest.com/dede/login.php@@userid=admin&pwd=tidus2005&gotopage=/dede/&dopost=login
 * 服务器验证登陆成功了, 并且在此次会话变量中增加了我们登陆成功的标识.
 *
 * 3,增加一个广告定义
 * 增加一个广告定义其实就是一个添加数据的过程,无非是我们把我们要添加的数据通过参数的形式告诉指定url页面,页面获取后添加到数据库去而已.
 * 此url地址为:
 * post@@http://www.51etest.com/dede/ad_add.php@@dopost=save&tagname=test&typeid=0&adname=test&starttime=2008-05-29
 * 因为这个页面会先判断我是否登陆
 * 而判断的依据,前面讲了,就是根据我请求时的SessionID找到指定的Session数据区中是否存在我的登陆信息,
 * 所以我当然要把访问登陆页面时获取的SessionID原封不动的再发回去
 * 相当于对服务器说,这是我刚刚来时,你发我的临时身份证,我现在可以形势我的权利。
 *
 * 这就是整个Java后台登陆网站,然后添加数据的过程。

 

Java代码 复制代码
  1. package cn.javadr.product;   
  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.OutputStream;   
  8. import java.net.HttpURLConnection;   
  9. import java.net.MalformedURLException;   
  10. import java.net.URL;   
  11. import java.net.URLConnection;   
  12. import java.util.HashMap;   
  13. import java.util.Iterator;   
  14. import java.util.Map;   
  15. import java.util.Map.Entry;   
  16.   
  17. /**  
  18.  * HttpClient  
  19.  *   
  20.  * @author Tang Ren email: <a  
  21.  *         href="mailto:tangren1206@163.com">tangren1206@163.com</a>  
  22.  *   
  23.  * <A href="mailto:post@@http://www.51etest.com/dede/login.php@@userid=xxxx&pwd=xxxxxx&gotopage=/dede/&dopost=login">post@@http://www.51etest.com/dede/login.php@@userid=xxxx&pwd=xxxxxx&gotopage=/dede/&dopost=login  
  24. </A> *   
  25.  * post@@http://www.51etest.com/dede/ad_add.php@@dopost=save&tagname=test&typeid=0&adname=test&starttime=2008-05-29  
  26.  * 20:58:25&endtime=2008-06-28 20:58:25×et=0&normbody=test&expbody=test  
  27.  *   
  28.  */  
  29.   
  30. /**  
  31.  *   
  32.  */  
  33. public class HttpClient {   
  34.   
  35.     private static final String USER_AGENT_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";   
  36.   
  37.     /**  
  38.      * Cmd splitor default is symbol '$$'.  
  39.      */  
  40.     private static final String HTTP_CLIENT_CMD_SPLITOR = "@@";   
  41.   
  42.     /**  
  43.      * Post parameter splitor default is symbol '&'.  
  44.      */  
  45.     private static final String POST_PARAMETER_SPLITOR = "&";   
  46.   
  47.     private static final String POST_PARAMETER_KV_SPLITOR = "=";   
  48.   
  49.     private String cookie = null;   
  50.   
  51.     private Map cookieMap = new HashMap();   
  52.   
  53.     public static void main(String[] args) {   
  54.         HttpClient client = new HttpClient();   
  55.     }   
  56.   
  57.     public HttpClient() {   
  58.         // Input http request url   
  59.   
  60.         BufferedReader consleReader = new BufferedReader(new InputStreamReader(   
  61.                 System.in));   
  62.         String httpResponse = null;   
  63.         String url = null;   
  64.         String cmd = null;   
  65.         String method = null;   
  66.         try {   
  67.             while (true) {   
  68.                 cmd = consleReader.readLine();   
  69.                 if (cmd.indexOf(HTTP_CLIENT_CMD_SPLITOR) == -1)   
  70.                     continue;   
  71.   
  72.                 method = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[0];   
  73.                 url = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[1];   
  74.                 if (method.toUpperCase().equals("GET")) {   
  75.                     httpResponse = this.getMethod(url, true);   
  76.                 } else if (method.toUpperCase().equals("POST")) {   
  77.                     Map parameters = this.parsePostParameters(cmd   
  78.                             .split(HTTP_CLIENT_CMD_SPLITOR)[2]);   
  79.                     httpResponse = this.postMethod(url, parameters, true);   
  80.                 }   
  81.                 System.out.println(httpResponse);   
  82.             }   
  83.         } catch (IOException e) {   
  84.             e.printStackTrace();   
  85.         } finally {   
  86.             try {   
  87.                 consleReader.close();   
  88.             } catch (IOException e) {   
  89.                 e.printStackTrace();   
  90.             }   
  91.         }   
  92.   
  93.     }   
  94.   
  95.     /**  
  96.      * Request specifid url with 'GET' method. And return HTTP response content.  
  97.      *   
  98.      * @param url  
  99.      * @return  
  100.      */  
  101.     private String getMethod(String url, boolean keepCookie) {   
  102.         if (url == null || url.length() == 0) {   
  103.             return "Requst url could not be null or empty.";   
  104.         }   
  105.   
  106.         StringBuffer result = new StringBuffer();   
  107.         try {   
  108.             HttpURLConnection httpURLConnection = this.getHttpURLConnection(   
  109.                     url, keepCookie);   
  110.   
  111.             // Set request properties.   
  112.             this.settingHttpRequestHeader(httpURLConnection);   
  113.   
  114.             httpURLConnection.setRequestMethod("GET");   
  115.   
  116.             // Getting or setting cookie   
  117.             this.gettingOrSettingCookie(httpURLConnection, keepCookie);   
  118.   
  119.             InputStream httpInputStream = httpURLConnection.getInputStream();   
  120.             BufferedReader httpBufferedReader = new BufferedReader(   
  121.                     new InputStreamReader(httpInputStream, "GBK"));   
  122.             result.append(this.readBufferedContent(httpBufferedReader));   
  123.   
  124.             // Connect to host.   
  125.             httpURLConnection.connect();   
  126.         } catch (IOException e) {   
  127.             e.printStackTrace();   
  128.             return "getHttpURLConnection failed.";   
  129.         }   
  130.         return result.toString();   
  131.     }   
  132.   
  133.     public String postMethod(String url, Map parameters, boolean keepCookie) {   
  134.         StringBuffer httpResponse = new StringBuffer();   
  135.   
  136.         HttpURLConnection httpURLConnection = null;   
  137.         OutputStream httpOutputStream = null;   
  138.         try {   
  139.             httpURLConnection = this.getHttpURLConnection(url, keepCookie);   
  140.             // Set request properties.   
  141.             this.settingHttpRequestHeader(httpURLConnection);   
  142.   
  143.             // Set request method with 'POST'   
  144.             httpURLConnection.setRequestMethod("POST");   
  145.   
  146.             // Set connection output is true.   
  147.             httpURLConnection.setDoOutput(true);   
  148.             // Getting or setting cookie   
  149.             this.gettingOrSettingCookie(httpURLConnection, keepCookie);   
  150.             // Get Http output stream   
  151.             httpOutputStream = httpURLConnection.getOutputStream();   
  152.   
  153.             // Build post parameters string   
  154.             StringBuffer postParams = new StringBuffer();   
  155.             int index = 0;   
  156.             for (Iterator<Entry> iter = parameters.entrySet().iterator(); iter   
  157.                     .hasNext(); index++) {   
  158.                 Entry<String, String> entry = iter.next();   
  159.                 postParams.append(index != 0 ? "&" : "");   
  160.                 postParams.append(entry.getKey());   
  161.                 postParams.append("=");   
  162.                 postParams.append(entry.getValue());   
  163.             }   
  164.             httpOutputStream.write(postParams.toString().getBytes());   
  165.   
  166.             BufferedReader httpBufferedReader = new BufferedReader(   
  167.                     new InputStreamReader(httpURLConnection.getInputStream()));   
  168.             httpResponse.append(this.readBufferedContent(httpBufferedReader));   
  169.         } catch (IOException e) {   
  170.             e.printStackTrace();   
  171.             return null;   
  172.         } finally {   
  173.             try {   
  174.                 httpOutputStream.close();   
  175.             } catch (IOException e) {   
  176.                 e.printStackTrace();   
  177.             }   
  178.         }   
  179.   
  180.         return httpResponse.toString();   
  181.     }   
  182.   
  183.     /**  
  184.      * Setting HTTP request header properties  
  185.      *   
  186.      * @param httpURLConnection  
  187.      */  
  188.     private void settingHttpRequestHeader(HttpURLConnection httpURLConnection) {   
  189.         if (httpURLConnection == null)   
  190.             return;   
  191.         httpURLConnection.setRequestProperty("User-Agent", USER_AGENT_VALUE);   
  192.         // TODO setting some other properties here . . .   
  193.     }   
  194.   
  195.     /**  
  196.      * Get HttpURLConnection by specified url string.  
  197.      *   
  198.      * @param url  
  199.      * @return  
  200.      * @throws IOException  
  201.      */  
  202.     private HttpURLConnection getHttpURLConnection(String url,   
  203.             boolean keepCookie) throws IOException {   
  204.         URL urlObj = new URL(url);   
  205.         URLConnection urlConnection = urlObj.openConnection();   
  206.         if (urlConnection instanceof HttpURLConnection)   
  207.             return (HttpURLConnection) urlConnection;   
  208.         throw new MalformedURLException();   
  209.     }   
  210.   
  211.     /**  
  212.      * Read bufferedReader buffered content.  
  213.      *   
  214.      * @param bufferedReader  
  215.      * @return  
  216.      */  
  217.     private String readBufferedContent(BufferedReader bufferedReader) {   
  218.         if (bufferedReader == null)   
  219.             return null;   
  220.         StringBuffer result = new StringBuffer();   
  221.         String line = null;   
  222.         try {   
  223.             while ((line = bufferedReader.readLine()) != null) {   
  224.                 result.append(line);   
  225.             }   
  226.         } catch (IOException e) {   
  227.             e.printStackTrace();   
  228.             return null;   
  229.         }   
  230.         return result.toString();   
  231.     }   
  232.   
  233.     /**  
  234.      * Parse and create parameter map with parameter string  
  235.      *   
  236.      * @param parameterString  
  237.      * @return  
  238.      */  
  239.     private Map parsePostParameters(String parameterString) {   
  240.         if (parameterString == null || parameterString.length() == 0)   
  241.             return null;   
  242.         Map result = new HashMap<String, String>();   
  243.   
  244.         // only one parameter key-value pair   
  245.         if (parameterString.indexOf(POST_PARAMETER_SPLITOR) == -1) {   
  246.             if (parameterString.indexOf(POST_PARAMETER_KV_SPLITOR) != -1)   
  247.                 result.put(parameterString.split(POST_PARAMETER_KV_SPLITOR)[0],   
  248.                         parameterString.split(POST_PARAMETER_KV_SPLITOR)[1]);   
  249.         } else {   
  250.             String[] keyValues = parameterString.split(POST_PARAMETER_SPLITOR);   
  251.             for (int i = 0; i < keyValues.length; i++) {   
  252.                 String keyValue = keyValues[i];   
  253.                 result.put(keyValue.split(POST_PARAMETER_KV_SPLITOR)[0],   
  254.                         keyValue.split(POST_PARAMETER_KV_SPLITOR)[1]);   
  255.             }   
  256.         }   
  257.         return result;   
  258.     }   
  259.   
  260.     /**  
  261.      * Get or set cookie.  
  262.      *   
  263.      * @param httpURLConnection  
  264.      * @param keepCookie  
  265.      */  
  266.     private void gettingOrSettingCookie(HttpURLConnection httpURLConnection,   
  267.             boolean keepCookie) {   
  268.         // Getting or setting cookie.   
  269.         if (cookie == null || cookie.length() == 0) {   
  270.             String setCookie = httpURLConnection.getHeaderField("Set-Cookie");   
  271.             cookie = setCookie.substring(0, setCookie.indexOf(";"));   
  272.         } else if (keepCookie) {   
  273.             httpURLConnection.setRequestProperty("Cookie", cookie);   
  274.         }   
  275.     }   
  276. }  

 

Java代码 复制代码
  1. 本人水平有限,大家如果有任何问题,欢迎和我讨论.  
Java代码 复制代码
  1. 联系方式Email: <A href="mailto:tangren1206@163.com">tangren1206@163.com</A>   
  2. QQ: 580126  
原创粉丝点击