欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java利用HttpClient模拟POST表单操作应用及注意事项

程序员文章站 2024-03-11 15:34:25
httpclient使用post方法提交数据 源代码: 复制代码 代码如下: package post; import java.io.ioexception; i...

httpclient使用post方法提交数据 源代码:

复制代码 代码如下:

package post;
import java.io.ioexception;
import org.apache.commons.httpclient.header;
import org.apache.commons.httpclient.httpclient;
import org.apache.commons.httpclient.httpexception;
import org.apache.commons.httpclient.httpstatus;
import org.apache.commons.httpclient.namevaluepair;
import org.apache.commons.httpclient.methods.postmethod;
public class posthttp {
 /**
  * @param args
  */
 public static void main(string[] args) {
  // todo auto-generated method stub
  httpclient httpclient = new httpclient();
  string url = "";
  postmethod postmethod = new postmethod(url);
//   填入各个表单域的值
  namevaluepair[] data = {
    new namevaluepair("id", "11"),
    new namevaluepair("mtg", "0"),
    new namevaluepair("havecookie", "0"),
    new namevaluepair("backid", "30"),
    new namevaluepair("psw", "password")
  };
//   将表单的值放入postmethod中
  postmethod.setrequestbody(data);
//   执行postmethod
  int statuscode = 0;
  try {
   statuscode = httpclient.executemethod(postmethod);
  } catch (httpexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  } catch (ioexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
//   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;
  }
  else
  {
         system.out.println(postmethod.getstatusline());
         string str = "";
         try {
               str = postmethod.getresponsebodyasstring();
         } catch (ioexception e) {
               // todo auto-generated catch block
               e.printstacktrace();
         }       
         system.out.println(str);
  }
  postmethod.releaseconnection();
        return ;
 }
}

//这是一个用户认证过程的登陆信息

其中需要的jar包:

1、commons-httpclient-3.1-rc1.zip

2、commons-codec-1.3.jar   

3、commons-logging-api.jar   在tomcat5.5中的tomcat 5.5/bin目录下或者