java编程中采用Apache common.httpclient方式模拟POST请求

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(2898)   2024-04-17 12:33:21
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;
	}
}
标签2: Java编程 Java post Apache
地址:https://www.leftso.com/article/155.html

相关阅读

java编程中采用Apache common.httpclient方式模拟POST请求
Java 10上的Apache CXF
Java编程软件有哪些?常用Java编程软件下载、安装和使用说明
Apache Shiro教程,您的第一个Apache Shiro应用程序(翻译)-编程技术
Apache httpclient4.5 GET/POST/PUT/OPTION/DELETE工具类
Java编程中使用POI框架以模板方式导出Excel文件,适合Excel比较复杂的情况
java编程之maven打包Java source jar包
Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用
java编程之java jwt token使用,autho0的Java-jwt框架使用,java编程,java-jwt
Java编程之java static关键字,Java编程,static关键字