Chinaunix首页 | 论坛 | 博客
  • 博客访问: 664023
  • 博文数量: 220
  • 博客积分: 10487
  • 博客等级: 上将
  • 技术积分: 2072
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-09 00:25
文章分类

全部博文(220)

文章存档

2012年(5)

2011年(38)

2010年(135)

2009年(42)

我的朋友

分类: Java

2010-11-15 16:01:13

好多天没时间认真的写篇文章了,这两天研究了下HTTPClient,做了个实用的博客小工具,能方便快速的发布文章.在此与大家分享.
 
先看看工具使用效果:
 
 
 
 
 
 
 
 
怎么样,效果还不错吧.我这里做的只是个最简单的应用,把平常浏览过程中发现的有价值,有意义的链接快速发布到我的博客上,下次浏览直接看就行了.因为有些原始文档是很难找到的.
 
现在来看下关键的实现过程
 
总的流程
 
 

public void start(){

        getCheckCookie(); //1.先获取 cookie,服务器会有cookie的验证
        login();          //2.登陆
        postArticle();    //3.发布

        start();          //循环,直至退出
    }

创建客户端

private void initClient(){
        client = new HttpClient();
        client.getParams().setSoTimeout(30000);
        client.getParams().setContentCharset("gbk");
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

获取cookie

/**
     * 获取验证Cookie
     *
     */

    private void getCheckCookie(){
        try {
            GetMethod index = new GetMethod("http://control.cublog.cn");
            client.executeMethod(index)
            index.releaseConnection();
        } catch (HttpException e) {
            System.out.println("连接失败:"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("连接失败:"+e.getMessage());
            e.printStackTrace();
        }
    }


登陆

/**
     * 开始登陆
     *
     */

    private void login(){
        try {
            PostMethod post = new PostMethod("http://control.cublog.cn/login.php");

            List<NameValuePair> paras = new ArrayList<NameValuePair>();
            paras.add(new NameValuePair("back","index.php"));
            paras.add(new NameValuePair("username","*****"));//值保密
            paras.add(new NameValuePair("password","*****"));//值保密
            paras.add(new NameValuePair("savecookie","1"));

            post.setRequestBody(paras.toArray(new NameValuePair[paras.size()]));
            client.executeMethod(post);
            post.releaseConnection();
        } catch (IllegalArgumentException e) {
            System.out.println("参数不合法:"+e.getMessage());
            e.printStackTrace();
        } catch (HttpException e) {
            System.out.println("连接失败:"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("连接失败:"+e.getMessage());
            e.printStackTrace();
        }
    }


 

开始发布文章

/**
     * 发布文章
     *
     */

    private void postArticle(){
        try {

            System.out.println("请输入文章名:");
            String articleTitle = scan.nextLine();
            if("".equals(articleTitle)){
                System.out.println("必须输入文章名,请重新输入!");
                postArticle();
                return;
            }

            System.out.println("请输入文章链接:");
            String articleLink = scan.nextLine();
            if("".equals(articleLink)){
                System.out.println("必须输入文章链接,请重新输入!");
                postArticle();
                return;
            }

            System.out.println("请选择文章分类:");
            int i=1;

             //是我自己的博客的文章分类id及名称,可通过浏览器访问后查看源代码整理出来
            for(NameValuePair pair:articleClassifyLst){
                System.out.println(i++ +":"+pair.getValue());
            }
            String articleType = scan.nextLine();

            //校验文章分类是否合法
            if(!articleType.matches("\\d+") || articleClassifyLst.get(Integer.parseInt(articleType)-1)==null){
                System.out.println("必须输入合法的文章分类,请重新输入!");
                postArticle();
                return;
            }

            List<NameValuePair> paras =new ArrayList<NameValuePair>();
            

            //发表文章

            PostMethod postBlog = new PostMethod("http://control.cublog.cn/article_insert.php");
            Cookie[] cookies = client.getState().getCookies();

            //很关键的步骤,登陆成功后添加cookie到post请求
            StringBuilder cookieValue = new StringBuilder();
            for(Cookie cookie : cookies){
                cookieValue.append(cookie.getName());
                cookieValue.append("=");
                cookieValue.append(cookie.getValue());
                cookieValue.append("; ");
            }

            //设置cookie
            postBlog.setRequestHeader("Cookie",cookieValue.toString());

            //构建提交参数,具体参数这里涉及服务器安全,这里不完全列出
            paras = new ArrayList<NameValuePair>();
            paras.add(new NameValuePair("frmid",articleClassifyLst.get(Integer.parseInt(articleType)-1).getName()));//文章分类
            paras.add(new NameValuePair("systemfrmid","20"));//系统分类
            paras.add(new NameValuePair("arttype","日记"));//文章类型
            paras.add(new NameValuePair("isshow","1"));//是否显示
            paras.add(new NameValuePair("pubdate","2010-11-14"));//发布日期
            ......


            postBlog.setRequestBody(paras.toArray(new NameValuePair[paras.size()]));

            //执行提交
            client.executeMethod(postBlog);

            //判断是否提交成功
            String postResult = postBlog.getResponseBodyAsString();
            if(postResult.indexOf("您的文章已经成功添加了")!=-1){
                System.out.println("文章发布成功,查看链接:");
                System.out.println("http://blog.chinaunix.net/u3/103146/article_"+articleClassifyLst.get(Integer.parseInt(articleType)-1).getName()+".html");
            }

            //通知client释放链接,具体是否释放由connectionManager决定
            postBlog.releaseConnection();
        } catch (IllegalArgumentException e) {
            System.out.println("参数不合法:"+e.getMessage());
            e.printStackTrace();
        } catch (HttpException e) {
            System.out.println("连接失败:"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("连接失败:"+e.getMessage());
            e.printStackTrace();
        }
    }

 

以上是整个程序的核心逻辑,HTTPClient对于java编程者来说,在处理模拟网络事件,以及了解http协议方面有较大的帮助.本人也是在积极学习当中.

再次申明:ChinaUnix为我们提供了一个非常理想的知识积累及共享平台,该程序只是出于方便个人发布文章而开发,希望不要被应用在博客群发之类的应用上.

之前我发过一篇用Python编写的自动发布的文章,如果使用Python 的Pamie,仅需不到30行代码即可实现本文所述功能,不过实现原理完全不一样,那个是完全对浏览器的操作.有兴趣可以看看.

Python+PAMIE+30行代码便能打造ChinaUnix博客小助手

阅读(703) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~