lee 910 0 2017-04-29 12:45:06

文章位置:左搜> 编程技术> 正文
java编程中采用Apache common.httpclient方式模拟POST请求
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

public class HttpclientUtils {

	/**
	 * 采用Apache common.httpclient方式模拟POST请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params) throws HttpException, IOException {
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");

		List<NameValuePair> dataList = new ArrayList<>();
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				dataList.add(new NameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		if (!dataList.isEmpty()) {
			method.setRequestBody(dataList.toArray(new NameValuePair[0]));
		}
		client.executeMethod(method);
		String SubmitResult = method.getResponseBodyAsString();

		return SubmitResult;
	}
}