首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

工具种发送http请求

2012-11-16 
工具类发送http请求import org.apache.commons.httpclient.methods.PostMethodimport org.apache.commons

工具类发送http请求



import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.HttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class PostHelper {
???
private static PostMethod method;
???
??? public PostHelper(String url){
??? ??? method = new PostMethod(url);
??? ??? method.addRequestHeader("Cache-Control", "no-cache");
??? ??? method.addRequestHeader("SOAPAction", """");
??? ??? method.addRequestHeader("Cookie", "JSESSIONID=A09JHGHKHU68624309UTY84932;");
??? ??? method.addRequestHeader("Host", "192.168.3.205");
??? ??? method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
??? }
???
??? public void addParameter(String paramName,String paramValue){
??? ??? method.addParameter(paramName, paramValue);
??? }
???
??? public static String post(String url)
??? ??? ??? throws IOException, UnsupportedEncodingException{
??? ???
??? ??? HttpClient httpClient = new HttpClient();
??? ??? httpClient.executeMethod(method);

??? ??? String result = "";
??? ??? if (method.getResponseContentLength() < 0) {
??? ??? ??? ByteArrayOutputStream bout = new ByteArrayOutputStream();
??? ??? ??? byte[] data = new byte[8192];
??? ??? ??? int rsize = 0;
??? ??? ??? int totalrsize = 0;
??? ??? ??? InputStream in = method.getResponseBodyAsStream();
??? ??? ??? do {
??? ??? ??? ??? rsize = in.read(data);
??? ??? ??? ??? if (rsize > 0) {
??? ??? ??? ??? ??? totalrsize += rsize;
??? ??? ??? ??? ??? bout.write(data, 0, rsize);
??? ??? ??? ??? }
??? ??? ??? } while (rsize > 0);
??? ??? ??? result = new String(bout.toByteArray());
??? ??? } else {
??? ??? ??? byte data[] = method.getResponseBody();
??? ??? ??? result=new String(data);
??? ??? }
??? ??? return result;
??? }

}

?

?

调用时

?

??? String url = "";
??? ??? ??? ??? PostHelper p = new PostHelper(url);
??? ??? ??? ??? p.addParameter("", );//设置参数
??? ??? ??? ??? p.addParameter("resultCode", "faile");
??? ??? ??? ???? p.post(url);

?

?

?

?

热点排行