Java发送form表单请求

maven地址
<dependency>
    <groupId>commons-httpclientgroupId>
    <artifactId>commons-httpclientartifactId>
    <version>3.1version>
dependency>
实现代码
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;

public class Test4 {
    public static void main(String[] args) throws IOException {
        PostMethod postMethod = null;
        postMethod = new PostMethod("http://pay.man317.com:3001/xh") ;
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
        //参数设置,需要注意的就是里边不能传NULL,要传空字符串
        NameValuePair[] data = {
                new NameValuePair("fee","19"),
                new NameValuePair("chooseType","1"),
                new NameValuePair("chooseValue","1")
        };

        postMethod.setRequestBody(data);

//            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        int res = httpClient.executeMethod(postMethod);// 执行POST方法
        Header[] responseHeaders = postMethod.getResponseHeaders();

        int statusCode = postMethod.getStatusCode();

        //设置编码格式,防止乱码,任意一种即可
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
//        httpClient.getParams().setContentCharset("UTF-8");
//        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

        String responseBodyAsString = postMethod.getResponseBodyAsString();

//        String result = new String(postMethod.getResponseBodyAsString().getBytes());

        System.out.println(res);
    }
}

你可能感兴趣的:(java)