- 浏览: 261584 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
zhagener:
package com.huawei.qyq.impl;imp ...
EasyMock使用说明 -
LetCode:
将String转换成InputStream -
Mr_kimilo:
MyEclipse6.5安装的时候出现问题: JS Test ...
javascript测试工具: JsTestDriver -
jersey109:
我同意楼下的,SQLException和IOException ...
check exception和uncheck exception -
jersey109:
楼主,你不说CODE,我觉得你对RuntimeExceptio ...
check exception和uncheck exception
* 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后台登陆网站,然后添加数据的过程。
- package cn.javadr.product;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- /**
- * HttpClient
- *
- * @author Tang Ren email: <a
- * href="mailto:tangren1206@163.com">tangren1206@163.com</a>
- *
- * <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
- </A> *
- * post@@http://www.51etest.com/dede/ad_add.php@@dopost=save&tagname=test&typeid=0&adname=test&starttime=2008-05-29
- * 20:58:25&endtime=2008-06-28 20:58:25×et=0&normbody=test&expbody=test
- *
- */
- /**
- *
- */
- public class HttpClient {
- private static final String USER_AGENT_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";
- /**
- * Cmd splitor default is symbol '$$'.
- */
- private static final String HTTP_CLIENT_CMD_SPLITOR = "@@";
- /**
- * Post parameter splitor default is symbol '&'.
- */
- private static final String POST_PARAMETER_SPLITOR = "&";
- private static final String POST_PARAMETER_KV_SPLITOR = "=";
- private String cookie = null;
- private Map cookieMap = new HashMap();
- public static void main(String[] args) {
- HttpClient client = new HttpClient();
- }
- public HttpClient() {
- // Input http request url
- BufferedReader consleReader = new BufferedReader(new InputStreamReader(
- System.in));
- String httpResponse = null;
- String url = null;
- String cmd = null;
- String method = null;
- try {
- while (true) {
- cmd = consleReader.readLine();
- if (cmd.indexOf(HTTP_CLIENT_CMD_SPLITOR) == -1)
- continue;
- method = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[0];
- url = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[1];
- if (method.toUpperCase().equals("GET")) {
- httpResponse = this.getMethod(url, true);
- } else if (method.toUpperCase().equals("POST")) {
- Map parameters = this.parsePostParameters(cmd
- .split(HTTP_CLIENT_CMD_SPLITOR)[2]);
- httpResponse = this.postMethod(url, parameters, true);
- }
- System.out.println(httpResponse);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- consleReader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Request specifid url with 'GET' method. And return HTTP response content.
- *
- * @param url
- * @return
- */
- private String getMethod(String url, boolean keepCookie) {
- if (url == null || url.length() == 0) {
- return "Requst url could not be null or empty.";
- }
- StringBuffer result = new StringBuffer();
- try {
- HttpURLConnection httpURLConnection = this.getHttpURLConnection(
- url, keepCookie);
- // Set request properties.
- this.settingHttpRequestHeader(httpURLConnection);
- httpURLConnection.setRequestMethod("GET");
- // Getting or setting cookie
- this.gettingOrSettingCookie(httpURLConnection, keepCookie);
- InputStream httpInputStream = httpURLConnection.getInputStream();
- BufferedReader httpBufferedReader = new BufferedReader(
- new InputStreamReader(httpInputStream, "GBK"));
- result.append(this.readBufferedContent(httpBufferedReader));
- // Connect to host.
- httpURLConnection.connect();
- } catch (IOException e) {
- e.printStackTrace();
- return "getHttpURLConnection failed.";
- }
- return result.toString();
- }
- public String postMethod(String url, Map parameters, boolean keepCookie) {
- StringBuffer httpResponse = new StringBuffer();
- HttpURLConnection httpURLConnection = null;
- OutputStream httpOutputStream = null;
- try {
- httpURLConnection = this.getHttpURLConnection(url, keepCookie);
- // Set request properties.
- this.settingHttpRequestHeader(httpURLConnection);
- // Set request method with 'POST'
- httpURLConnection.setRequestMethod("POST");
- // Set connection output is true.
- httpURLConnection.setDoOutput(true);
- // Getting or setting cookie
- this.gettingOrSettingCookie(httpURLConnection, keepCookie);
- // Get Http output stream
- httpOutputStream = httpURLConnection.getOutputStream();
- // Build post parameters string
- StringBuffer postParams = new StringBuffer();
- int index = 0;
- for (Iterator<Entry> iter = parameters.entrySet().iterator(); iter
- .hasNext(); index++) {
- Entry<String, String> entry = iter.next();
- postParams.append(index != 0 ? "&" : "");
- postParams.append(entry.getKey());
- postParams.append("=");
- postParams.append(entry.getValue());
- }
- httpOutputStream.write(postParams.toString().getBytes());
- BufferedReader httpBufferedReader = new BufferedReader(
- new InputStreamReader(httpURLConnection.getInputStream()));
- httpResponse.append(this.readBufferedContent(httpBufferedReader));
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- } finally {
- try {
- httpOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return httpResponse.toString();
- }
- /**
- * Setting HTTP request header properties
- *
- * @param httpURLConnection
- */
- private void settingHttpRequestHeader(HttpURLConnection httpURLConnection) {
- if (httpURLConnection == null)
- return;
- httpURLConnection.setRequestProperty("User-Agent", USER_AGENT_VALUE);
- // TODO setting some other properties here . . .
- }
- /**
- * Get HttpURLConnection by specified url string.
- *
- * @param url
- * @return
- * @throws IOException
- */
- private HttpURLConnection getHttpURLConnection(String url,
- boolean keepCookie) throws IOException {
- URL urlObj = new URL(url);
- URLConnection urlConnection = urlObj.openConnection();
- if (urlConnection instanceof HttpURLConnection)
- return (HttpURLConnection) urlConnection;
- throw new MalformedURLException();
- }
- /**
- * Read bufferedReader buffered content.
- *
- * @param bufferedReader
- * @return
- */
- private String readBufferedContent(BufferedReader bufferedReader) {
- if (bufferedReader == null)
- return null;
- StringBuffer result = new StringBuffer();
- String line = null;
- try {
- while ((line = bufferedReader.readLine()) != null) {
- result.append(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- return result.toString();
- }
- /**
- * Parse and create parameter map with parameter string
- *
- * @param parameterString
- * @return
- */
- private Map parsePostParameters(String parameterString) {
- if (parameterString == null || parameterString.length() == 0)
- return null;
- Map result = new HashMap<String, String>();
- // only one parameter key-value pair
- if (parameterString.indexOf(POST_PARAMETER_SPLITOR) == -1) {
- if (parameterString.indexOf(POST_PARAMETER_KV_SPLITOR) != -1)
- result.put(parameterString.split(POST_PARAMETER_KV_SPLITOR)[0],
- parameterString.split(POST_PARAMETER_KV_SPLITOR)[1]);
- } else {
- String[] keyValues = parameterString.split(POST_PARAMETER_SPLITOR);
- for (int i = 0; i < keyValues.length; i++) {
- String keyValue = keyValues[i];
- result.put(keyValue.split(POST_PARAMETER_KV_SPLITOR)[0],
- keyValue.split(POST_PARAMETER_KV_SPLITOR)[1]);
- }
- }
- return result;
- }
- /**
- * Get or set cookie.
- *
- * @param httpURLConnection
- * @param keepCookie
- */
- private void gettingOrSettingCookie(HttpURLConnection httpURLConnection,
- boolean keepCookie) {
- // Getting or setting cookie.
- if (cookie == null || cookie.length() == 0) {
- String setCookie = httpURLConnection.getHeaderField("Set-Cookie");
- cookie = setCookie.substring(0, setCookie.indexOf(";"));
- } else if (keepCookie) {
- httpURLConnection.setRequestProperty("Cookie", cookie);
- }
- }
- }
package cn.javadr.product; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * HttpClient * * @author Tang Ren email: <a * href="mailto:tangren1206@163.com">tangren1206@163.com</a> * * post@@http://www.51etest.com/dede/login.php@@userid=xxxx&pwd=xxxxxx&gotopage=/dede/&dopost=login * * post@@http://www.51etest.com/dede/ad_add.php@@dopost=save&tagname=test&typeid=0&adname=test&starttime=2008-05-29 * 20:58:25&endtime=2008-06-28 20:58:25×et=0&normbody=test&expbody=test * */ /** * */ public class HttpClient { private static final String USER_AGENT_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)"; /** * Cmd splitor default is symbol '$$'. */ private static final String HTTP_CLIENT_CMD_SPLITOR = "@@"; /** * Post parameter splitor default is symbol '&'. */ private static final String POST_PARAMETER_SPLITOR = "&"; private static final String POST_PARAMETER_KV_SPLITOR = "="; private String cookie = null; private Map cookieMap = new HashMap(); public static void main(String[] args) { HttpClient client = new HttpClient(); } public HttpClient() { // Input http request url BufferedReader consleReader = new BufferedReader(new InputStreamReader( System.in)); String httpResponse = null; String url = null; String cmd = null; String method = null; try { while (true) { cmd = consleReader.readLine(); if (cmd.indexOf(HTTP_CLIENT_CMD_SPLITOR) == -1) continue; method = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[0]; url = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[1]; if (method.toUpperCase().equals("GET")) { httpResponse = this.getMethod(url, true); } else if (method.toUpperCase().equals("POST")) { Map parameters = this.parsePostParameters(cmd .split(HTTP_CLIENT_CMD_SPLITOR)[2]); httpResponse = this.postMethod(url, parameters, true); } System.out.println(httpResponse); } } catch (IOException e) { e.printStackTrace(); } finally { try { consleReader.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Request specifid url with 'GET' method. And return HTTP response content. * * @param url * @return */ private String getMethod(String url, boolean keepCookie) { if (url == null || url.length() == 0) { return "Requst url could not be null or empty."; } StringBuffer result = new StringBuffer(); try { HttpURLConnection httpURLConnection = this.getHttpURLConnection( url, keepCookie); // Set request properties. this.settingHttpRequestHeader(httpURLConnection); httpURLConnection.setRequestMethod("GET"); // Getting or setting cookie this.gettingOrSettingCookie(httpURLConnection, keepCookie); InputStream httpInputStream = httpURLConnection.getInputStream(); BufferedReader httpBufferedReader = new BufferedReader( new InputStreamReader(httpInputStream, "GBK")); result.append(this.readBufferedContent(httpBufferedReader)); // Connect to host. httpURLConnection.connect(); } catch (IOException e) { e.printStackTrace(); return "getHttpURLConnection failed."; } return result.toString(); } public String postMethod(String url, Map parameters, boolean keepCookie) { StringBuffer httpResponse = new StringBuffer(); HttpURLConnection httpURLConnection = null; OutputStream httpOutputStream = null; try { httpURLConnection = this.getHttpURLConnection(url, keepCookie); // Set request properties. this.settingHttpRequestHeader(httpURLConnection); // Set request method with 'POST' httpURLConnection.setRequestMethod("POST"); // Set connection output is true. httpURLConnection.setDoOutput(true); // Getting or setting cookie this.gettingOrSettingCookie(httpURLConnection, keepCookie); // Get Http output stream httpOutputStream = httpURLConnection.getOutputStream(); // Build post parameters string StringBuffer postParams = new StringBuffer(); int index = 0; for (Iterator<Entry> iter = parameters.entrySet().iterator(); iter .hasNext(); index++) { Entry<String, String> entry = iter.next(); postParams.append(index != 0 ? "&" : ""); postParams.append(entry.getKey()); postParams.append("="); postParams.append(entry.getValue()); } httpOutputStream.write(postParams.toString().getBytes()); BufferedReader httpBufferedReader = new BufferedReader( new InputStreamReader(httpURLConnection.getInputStream())); httpResponse.append(this.readBufferedContent(httpBufferedReader)); } catch (IOException e) { e.printStackTrace(); return null; } finally { try { httpOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return httpResponse.toString(); } /** * Setting HTTP request header properties * * @param httpURLConnection */ private void settingHttpRequestHeader(HttpURLConnection httpURLConnection) { if (httpURLConnection == null) return; httpURLConnection.setRequestProperty("User-Agent", USER_AGENT_VALUE); // TODO setting some other properties here . . . } /** * Get HttpURLConnection by specified url string. * * @param url * @return * @throws IOException */ private HttpURLConnection getHttpURLConnection(String url, boolean keepCookie) throws IOException { URL urlObj = new URL(url); URLConnection urlConnection = urlObj.openConnection(); if (urlConnection instanceof HttpURLConnection) return (HttpURLConnection) urlConnection; throw new MalformedURLException(); } /** * Read bufferedReader buffered content. * * @param bufferedReader * @return */ private String readBufferedContent(BufferedReader bufferedReader) { if (bufferedReader == null) return null; StringBuffer result = new StringBuffer(); String line = null; try { while ((line = bufferedReader.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); return null; } return result.toString(); } /** * Parse and create parameter map with parameter string * * @param parameterString * @return */ private Map parsePostParameters(String parameterString) { if (parameterString == null || parameterString.length() == 0) return null; Map result = new HashMap<String, String>(); // only one parameter key-value pair if (parameterString.indexOf(POST_PARAMETER_SPLITOR) == -1) { if (parameterString.indexOf(POST_PARAMETER_KV_SPLITOR) != -1) result.put(parameterString.split(POST_PARAMETER_KV_SPLITOR)[0], parameterString.split(POST_PARAMETER_KV_SPLITOR)[1]); } else { String[] keyValues = parameterString.split(POST_PARAMETER_SPLITOR); for (int i = 0; i < keyValues.length; i++) { String keyValue = keyValues[i]; result.put(keyValue.split(POST_PARAMETER_KV_SPLITOR)[0], keyValue.split(POST_PARAMETER_KV_SPLITOR)[1]); } } return result; } /** * Get or set cookie. * * @param httpURLConnection * @param keepCookie */ private void gettingOrSettingCookie(HttpURLConnection httpURLConnection, boolean keepCookie) { // Getting or setting cookie. if (cookie == null || cookie.length() == 0) { String setCookie = httpURLConnection.getHeaderField("Set-Cookie"); cookie = setCookie.substring(0, setCookie.indexOf(";")); } else if (keepCookie) { httpURLConnection.setRequestProperty("Cookie", cookie); } } }
发表评论
-
tomcat源码—redirect和forward的实现
2009-12-29 13:24 1369网上已经有很多关于redirect和forward区别的文章, ... -
深入浅出URL编码
2009-12-24 14:18 928一、问题: 编码问题是JAVA初学者在web开发 ... -
HttpServletResponse
2009-12-10 10:46 2871HttpServletResponseWeb服务器会送给Web ... -
给servlet写单元测试的总结
2009-11-11 10:05 915servlet的测试一般来说需要容器的支持,不是像通常的jav ... -
使用HttpURLConnection类(利用sessionId保持会话)
2009-11-04 16:15 2692TestServlet.java package nj. ... -
jsessionid传递方式对session实现机制
2009-11-04 16:12 4405<script type="text/j ... -
Servlet中web请求的编码
2009-10-23 16:13 753Servlet中Web请求的编码是一个很伤脑筋的问题。使用多个 ... -
Servlet,Filter的url-pattern详解
2009-10-12 13:54 1910Servlet的url匹配以 ... -
使用HttpURLConnection访问web页面
2009-10-10 15:48 1507URLConnection类给应用程序和web资源之间架设起了 ...
相关推荐
以上就是使用Java后台请求HTTP并保持Session的基本步骤。在实际应用中,可能需要考虑更多细节,比如异常处理、超时设置、重试策略等。在处理多个请求时,可能需要管理多个连接,这时可以使用线程池或者HTTP客户端库...
以上就是Java后台通过HTTP请求获取登录权限网站数据的基本步骤,包括GET和POST请求的实现以及Session的管理和保持。在实际应用中,可能还需要处理重定向、超时、错误处理等复杂情况,但这些基础内容已经为你构建了...
Java Web后端开发是互联网应用开发中的重要环节,Servlet技术是Java EE标准中用于构建动态网站的核心组件之一。本篇文章将深入探讨如何使用Servlet来实现网站后台的功能。 Servlet是Java编程语言中的一个接口,它...
开发者可以通过JSP的内置对象如request、response、session等来处理HTTP请求,以及通过EL(Expression Language)和JSTL(JavaServer Pages Standard Tag Library)简化页面逻辑。 其次,`Servlet`是Java EE中的...
在这个项目中,前端可能通过一个JSP(JavaServer Pages)页面,如`showReport.jsp`,来展示报表并发起请求到后台的Servlet来获取或处理出库数据。Servlet是Java Web开发中的一个重要组件,它负责处理HTTP请求,执行...
通过上述知识点,你可以开始构建一个简单的基于Java的JSP表单程序,从接收用户输入、验证数据到与数据库交互,实现一个完整的Web应用程序。记得在实践中不断学习和优化,提升你的Java Web开发技能。
2. ModelAndView对象:Spring MVC中的ModelAndView对象允许开发者将数据添加到模型中,然后在视图中访问。例如: ```java @RequestMapping("/show") public ModelAndView showUser() { ModelAndView modelAndView ...
12. Ajax总结:Ajax(异步JavaScript和XML)技术通过在后台与服务器进行少量数据交换,实现了网页的部分更新,提升了用户体验。 13. JSP九大隐式对象中四个作用域的大小与作用范围:page, request, session, ...
本文将详细介绍如何通过微信小程序调用微信登录功能获取openid,并利用Java作为服务端进行处理的步骤。 1. **调用微信登录获取code** 微信小程序提供了一个`wx.login`接口,用于获取用户的临时登录凭证——code。...
开发者可以使用JSP内置对象(如request、response、session等)来处理HTTP请求,获取或设置请求参数,以及与后台JavaBean或Servlet进行交互。 【LoginServlet】 在给定的压缩包文件中,"LoginServlet"很可能是一个...
【Java网上购物系统】是一个基于JSP(JavaServer Pages)技术构建的Web应用程序,主要用于模拟实现电子商务中的在线购物功能。JSP是Java EE平台的一部分,它允许开发者在HTML页面中嵌入Java代码,以实现动态网页的...
具体实现过程中,当学生提交选课请求时,JSP页面通过POST方法将请求发送到JAVA后台,后台通过JDBC连接数据库,查询学生是否满足选课条件,如是否已达到最大选课数、课程是否已满员等。如果符合条件,就更新选课关系...
例如,当用户点击“添加到购物车”按钮时,会发送一个POST请求到服务器,Servlet接收到这个请求后,解析请求参数,获取商品ID,然后从数据库中查询商品信息并添加到Session中。 3. **数据库交互**:为了获取商品...
page 作用域表示当前 JSP 页面,request 作用域表示当前请求,session 作用域表示当前会话,application 作用域表示当前应用程序。 List,Set,Collection,Collections List、Set、Collection 和 Collections 都是 ...
13. Spring MVC 中的默认参数类型:HttpServletRequest 通过 request 对象获取请求信息,HttpServletResponse 通过 response 处理响应信息,HttpSession 通过 session 对象得到 session 中存放的对象,Model/...
2. B/S结构的处理过程:用户通过浏览器发送HTTP请求到服务器,服务器接收到请求后解析请求内容,调用相应的后台服务处理,然后将处理结果以HTML或其他格式的响应返回给客户端浏览器,浏览器再解析并展示给用户。...
request对象用于获取客户端请求信息,response对象负责设置和发送响应,session和application对象则管理会话状态,保持用户信息跨页面传递。 4. 数据库连接与操作: 留言板通常需要存储用户的留言信息,因此可能...
- 数据被发送到服务器,通常是通过HTTP POST请求。 - 服务器接收到请求后,验证用户名和密码的正确性。 - 如果验证成功,服务器会创建一个session(会话),并可能设置session属性以标识已登录的用户。 - 验证失败则...
3. 使用Java代码传值:使用Java代码来传递数据,例如:servlet只能接收到session.setAttribute("testSession","Hello session")的内容,而不能接收到request的内容。 总结 getParameter()方法传递的是字符串,一般...