Java后台POST请求以application/x-www-form-urlencoded;charset=utf-8格式

引入依赖:


    commons-httpclient
    commons-httpclient
    3.1

Java 代码

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;


private String post(String postURL,String name,String age) throws Exception{
	PostMethod postMethod = new PostMethod(postURL) ;
	postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
	//参数设置,需要注意的就是里边不能传NULL,要传空字符串
	NameValuePair[] data = {
		new NameValuePair("name",name),
		new NameValuePair("age",age)
	};
	postMethod.setRequestBody(data);
    org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
	httpClient.executeMethod(postMethod);
	String result = postMethod.getResponseBodyAsString() ;
	return result;
}

 

你可能感兴趣的:(杂文)