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

需要使用的jar包

  • httpcore-4.4.4.jar
  • httpclient-4.5.2.jar
  • fastjson-1.2.47.jar


    org.apache.httpcomponents
    httpcore
    4.4.4



    org.apache.httpcomponents
    httpclient
    4.5.2


	com.alibaba
	fastjson
	1.2.47

示例代码
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 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 nameValuePairs = new ArrayList();
			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 "获取数据错误";
	}

你可能感兴趣的:(HttpClient)