当前位置:首页 > JSP教程 > JSP常见问题

jsp 中HttpClient中的POST方法实例详解

jsp 中httpclient中的post方法实例详解

post方法用来向目的服务器发出请求,要求它接受被附在请求后的实体,并把它当作请求队列(request-line)中请求uri所指定资源的附加新子项。post被设计成用统一的方法实现下列功能:

  • 对现有资源的注释
  • 向电子公告栏、新闻组,邮件列表或类似讨论组发送消息
  • 提交数据块,如将表单的结果提交给数据处理过程
  • 通过附加操作来扩展数据库
  • 调用httpclient中的postmethod与getmethod类似,除了设置postmethod的实例与getmethod有些不同之外,剩下的步骤都差不多。

    构造postmethod之前的步骤都相同,与getmethod一样,构造postmethod也需要一个uri参数,在本例中,登录的地址是http://www.newsmth.net/bbslogin2.php。在创建了postmethod的实例之后,需要给method实例填充表单的值,在bbs的登录表单中需要有两个域,第一个是用户名(域名叫id),第二个是密码(域名叫passwd)。表单中的域用类namevaluepair来表示,该类的构造函数第一个参数是域名,第二参数是该域的值;将表单所有的值设置到postmethod中用方法setrequestbody。另外由于bbs登录成功后会转向另外一个页面,但是httpclient对于要求接受后继服务的请求,比如post和put,不支持自动转发,因此需要自己对页面转向做处理。具体的页面转向处理请参见下面的"自动转向"部分。代码如下:

    string url = "http://www.newsmth.net/bbslogin2.php"; 
    postmethod postmethod = new postmethod(url); 
    // 填入各个表单域的值 
    namevaluepair[] data = { new namevaluepair("id", "youusername"), 
    new namevaluepair("passwd", "yourpwd") }; 
    // 将表单的值放入postmethod中 
    postmethod.setrequestbody(data); 
    // 执行postmethod 
    int statuscode = httpclient.executemethod(postmethod); 
    // httpclient对于要求接受后继服务的请求,象post和put等不能自动处理转发 
    // 301或者302 
    if (statuscode == httpstatus.sc_moved_permanently ||  
    statuscode == httpstatus.sc_moved_temporarily) { 
      // 从头中取出转向的地址 
      header locationheader = postmethod.getresponseheader("location"); 
      string location = null; 
      if (locationheader != null) { 
       location = locationheader.getvalue(); 
       system.out.println("the page was redirected to:" + location); 
      } else { 
       system.err.println("location field value is null."); 
      } 
      return; 
    } 
    

    感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


    【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

    相关教程推荐

    其他课程推荐