工具类发送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);

 

 

 

 

你可能感兴趣的:(http)