您的位置:首页 > 理论基础 > 计算机网络

使用httpClient3.1完成模拟浏览器登录上传下载总结

2008-03-11 15:44 761 查看
最近在使用apache得httpclient,本意是要编写一个软件,模拟浏览器登陆,上传文件,下载文件............要总结一些使用的经验..............首先是对http协议要有所了解,http传输总体就2部分,httpheader和httpbody,就跟人一样,分成头和身体部分,httpheader呢,包括一些浏览器阿,请求地址阿,类型阿,最重要的是cookie,因为cookie包含有敏感信息,比如用户名字和密码之类。。。听闻cookie还有加密的,幸亏我模拟登陆的网站的不是加密的httpbody么,就是一些html阿,jpg阿,视频文件。。。。。一些我们通常在浏览器看到的东西。要想模拟人家,就得知到人家长什么样子。。。。这样我们的抓包软件Ethereal就出马了通过抓包,我们知道要请求的地址阿,返回的细节,一切一切都赤裸裸地给我们窥探到了....能看到,就用办法了,哈哈注意,httpclient需要额外的commons-logging.jar,commons-codec-1.3.jar这个在apache都能下到。首先,登陆的请求可不只是用户名字和密码这么简单,还有些藏匿的信息,如果他们加上图片的认证,偶就头大了,幸好也没有......抓包知道要post得数据,通过正则我解析出来然后利用httpclient得PostMethod就进行请求......说到这里,需要说的是,httpclient的自动转向有点问题,需要修改源代码。。。我哪有这个胆子,没办法,我采取关闭自动转向,然后自写了一个自动转向得函数,虽然丑陋了点,但是终究是屋里人.......知道张什么样子...登陆了,就可以上传文件了,麻烦来了,httpclient不支持中文.... 我想,NND,还是得去该源代码, 但是等等,google出来一个牛人,重写了
PostMethod得
getRequestCharSet的方法...
public static class UTF8PostMethod extends PostMethod{
         public UTF8PostMethod(String url){
             super(url);
         }
         @Override
         public String getRequestCharSet() {
             //return super.getRequestCharSet();
             return "UTF-8";
         }
haha  ,搞定
使用的是MultipartPostMethod mPost = new MultipartPostMethod(url); NameValuePair title = new NameValuePair("title",this.getTitle());// NameValuePair detail = new NameValuePair("detail",this.getDetail());//" NameValuePair channel = new NameValuePair("channel",this.getChannel());//"14");//NameValuePair submit=new NameValuePair("submit","下一步"); UTF8PostMethod publishset=new UTF8PostMethod("http://www.tudou.com/my/program/publish.php"); publishset.setRequestBody(new NameValuePair[]{title,detail,。。。。});。。。。。。 UTF8PostMethod filePost = new UTF8PostMethod(uploadUrl); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,true); filePost.setParameter("Accept-Charset", "gb2312,utf-8;q=0.7,*;q=0.7"); filePost.setParameter("Accept-Language", "zh-cn,zh;q=0.5"); File targetFile=new File(this.getFilePath());//"E:/goforit.wmv"); MyLog.log("Uploading " + targetFile.getAbsolutePath() + " to " + uploadUrl); try { Part[] part={new FilePart("file", targetFile), //new StringPart("Content-Type", "video/x-ms-wmv"), }; filePost.setRequestEntity(new MultipartRequestEntity(part, filePost.getParams())); } catch (FileNotFoundException e){ MyLog.log(e.getMessage()); }。。。。。。。。。。。哈哈................还有需要注意的是,正则表达式的强大本来我是写一些html得解析类来处理返回数据,但是不要太麻烦了......使用正则,一切都简单了,但是java得正则。。。。。有点不熟,但问题还是解决了使用下载功能就简单了......只要判断出来返回的是视频流,就InputStream in = HttpMethod.getResponseBodyAsStream(); 保存就ok拉

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: