/** * 发布文章 * */ 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(); } }
|