posts - 23,comments - 66,trackbacks - 0
from:http://blog.csdn.net/ambitiontan/archive/2006/01/05/571272.aspx

服务器:
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 2006-03-21 21:44 rd2pm 阅读(2263) 评论(1)  编辑  收藏

FeedBack:
# re: 用JAVA模拟POST发送数据
2006-12-20 09:36 | 王建平
你的HttpRequest 在那个包里面?
  回复  更多评论
  

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


网站导航: