konhon

忘掉過去,展望未來。找回自我,超越自我。
逃避不一定躲的过, 面对不一定最难过, 孤单不一定不快乐, 得到不一定能长久, 失去不一定不再拥有, 可能因为某个理由而伤心难过, 但我却能找个理由让自己快乐.

Google

BlogJava 首页 新随笔 联系 聚合 管理
  203 Posts :: 0 Stories :: 61 Comments :: 0 Trackbacks

服务器:
1.jsp
<body>
<form name="_ctl0" method="post" action="TestFileManager.aspx" id="_ctl0" enctype="multipart/form-data">
<input type="hidden" name="__VIEWSTATE" value="dDwyNTIzNjA5NDU7Oz7rsE3eBYzQHDVtl+aTn96MvQW6PQ==" />
<p>
<input name="uploadfile1" id="uploadfile1" type="file" size="49" />
<input type="submit" name="Button1" value="?" id="Button1" />
</p>
<p>
<span id="Label1" style="width:459px;"></span>
</p>
<!-- Insert content here -->
</form>
</body>
客户端:
首先创建一个到服务器http的请求
HttpRequest request = new HttpRequest("http://服务器/1.jsp");
第一次使用的是GET方式
request.setMethod("GET");
紧接着进行一些请求的属性设置
request.setRequestHeader("Cache-Control", "no-cache");
这里保持连接,因为后面还要发送数据到服务器呢
request.setRequestHeader("Connection", "Keep-Alive");
下面是一些无关紧要的属性设置了。
request.setRequestHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
request.setRequestHeader("Accept-Encoding", "gzip, deflate");
request.setRequestHeader("Accept-Language", "en-au");
request.setRequestHeader("Referer", "http://服务器/1.jsp");
request.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3215; .NET CLR 1.0.3705)");
构造好了连接请求,然后连接
request.connect();
紧接着提取Cookie值,在后文的post中可以用到。
String strCookie = request.getResponseHeader("Set-Cookie");
strCookie = strCookie.substring(0,strCookie.indexOf(";"));
下面通过循环查找,提取__VIEWSTATE的值
for ( int i = 0; i < nlist.getLength(); i++) {
node = nlist.item(i);
strName = getNodeAttributeValue(node,"name");
if ( strName.equals("__VIEWSTATE") ) {
strValue = getNodeAttributeValue(node,"value");
break;
}
}
往服务器组织发送数据
DataOutputStream dos = new DataOutputStream(request.getOutputStream());
dos.writeBytes("-----------------------------"+strBoundary);//这是每个要被发送数据间的间隔
dos.writeBytes(" Content-Disposition: form-data; name="__VIEWSTATE"");
dos.writeBytes(" "+strValue);
dos.writeBytes(" -----------------------------"+strBoundary);
这里面是发送文件的部分
dos.writeBytes(" Content-Disposition: form-data; name="uploadfile1"; filename="" + strFileName + """);
dos.writeBytes(" Content-Type: text/xml");
dos.writeBytes(" ");
dos.writeBytes(new String(data));
dos.writeBytes(" -----------------------------"+strBoundary);
dos.writeBytes(" Content-Disposition: form-data; name="Button1"");
dos.writeBytes(" 上传");
dos.writeBytes(" -----------------------------"+strBoundary+"--");
dos.writeBytes(" ");
dos.close();
posted on 2007-03-07 20:14 konhon 优华 阅读(4244) 评论(1)  编辑  收藏

Feedback

# re: 用JAVA模拟POST发送数据 [未登录] 2009-05-12 03:42 ck
HttpRequest是什么东西呢?  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: