HttpClient Post 以表单提交方式请求带参数

需要使用的jar包

  • httpcore-4.4.4.jar
  • httpclient-4.5.2.jar
  • fastjson-1.2.47.jar
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.47</version>
</dependency>

示例代码
url:请求路径地址
mapdata : 请求携带参数

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

public String getContent(String url, Map<String, String> mapdata) {
//		System.out.println(url);
//		System.out.println(mapdata.toString());
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httpPost = new HttpPost(url);
		try {
			// 设置提交方式
			httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
			// 添加参数
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (mapdata.size() != 0) {
				// 将mapdata中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
				Set keySet = mapdata.keySet();
				Iterator it = keySet.iterator();
				while (it.hasNext()) {
					String k = (String) it.next();// key
					String v = mapdata.get(k);// value
					nameValuePairs.add(new BasicNameValuePair(k, v));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			System.out.println("nameValuePairs:" + nameValuePairs);
			// 执行http请求
			response = httpClient.execute(httpPost);
			// 获得http响应体
			HttpEntity entity = response.getEntity();
			System.out.println("entity:" + entity);
			if (entity != null) {
				// 响应的结果
				String content = EntityUtils.toString(entity, "UTF-8");
				System.out.println("content" + content);
				return content;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "获取数据错误";
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值