Java利用HttpClient模拟POST表单操作应用及注意事项
HttpClient使用post方法提交数据源代码:
packagepost; importJava.io.IOException; importorg.apache.commons.httpclient.Header; importorg.apache.commons.httpclient.HttpClient; importorg.apache.commons.httpclient.HttpException; importorg.apache.commons.httpclient.HttpStatus; importorg.apache.commons.httpclient.NameValuePair; importorg.apache.commons.httpclient.methods.PostMethod; publicclassPostHttp{ /** *@paramargs */ publicstaticvoidmain(String[]args){ //TODOAuto-generatedmethodstub HttpClienthttpClient=newHttpClient(); Stringurl="http://193.167.13.21/setup.cgi"; PostMethodpostMethod=newPostMethod(url); // 填入各个表单域的值 NameValuePair[]data={ newNameValuePair("ID","11"), newNameValuePair("mtg","0"), newNameValuePair("haveCookie","0"), newNameValuePair("backID","30"), newNameValuePair("psw","password") }; // 将表单的值放入postMethod中 postMethod.setRequestBody(data); // 执行postMethod intstatusCode=0; try{ statusCode=httpClient.executeMethod(postMethod); }catch(HttpExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发 // 301或者302 if(statusCode==HttpStatus.SC_MOVED_PERMANENTLY||statusCode==HttpStatus.SC_MOVED_TEMPORARILY) { // 从头中取出转向的地址 HeaderlocationHeader=postMethod.getResponseHeader("location"); Stringlocation=null; if(locationHeader!=null){ location=locationHeader.getValue(); System.out.println("Thepagewasredirectedto:"+location); } else{ System.err.println("Locationfieldvalueisnull."); } return; } else { System.out.println(postMethod.getStatusLine()); Stringstr=""; try{ str=postMethod.getResponseBodyAsString(); }catch(IOExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } System.out.println(str); } postMethod.releaseConnection(); return; } }
//这是一个用户认证过程的登陆信息
其中需要的jar包:
1、commons-httpclient-3.1-rc1.ziphttp://jakarta.apache.org/commons/httpclient/downloads.html
2、commons-codec-1.3.jar http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi
3、commons-logging-api.jar 在tomcat5.5中的Tomcat5.5/bin目录下或者 http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi