httpclient4.5使用详解 httpclient 4.5 post传递json参数

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(1996)   2024-04-19 10:13:19

httpclient4.5使用详解 httpclient 4.5 post传递json参数

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
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;

/**
 * 工具类 httpclient4.5
 * 
 * @author xq
 *
 */
public class HttpclientUtils {
	/**
	 * post请求 json参数
	 * 
	 * @param url
	 * @param bodyJsonParams
	 * @param headers
	 * @return
	 * @throws IOException
	 */
	public static String doPost(String url, String bodyJsonParams, Map<String, String> headers) throws IOException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json");
		httpPost.setEntity(new StringEntity(bodyJsonParams));

		if (headers != null && headers.keySet().isEmpty()) {
			Set<String> keySet = headers.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = headers.get(key);
				httpPost.addHeader(key, value);
			}

		}
		return execute(httpPost);
	}

	/**
	 * post k-v参数
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params, Map<String, String> headers)
			throws IOException {
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.keySet().isEmpty()) {
			List<NameValuePair> list = new ArrayList<>();

			Set<String> keySet = headers.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = headers.get(key);
				list.add(new BasicNameValuePair(key, value));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(list));
		}

		if (headers != null && headers.keySet().isEmpty()) {
			Set<String> keySet = headers.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = headers.get(key);
				httpPost.addHeader(key, value);
			}

		}
		return execute(httpPost);
	}

	/**
	 * get请求
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String doGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
		// 参数
		StringBuilder paramsBuilder = new StringBuilder(url);

		if (params != null && params.keySet().isEmpty()) {
			if (url.indexOf("?") == -1) {
				paramsBuilder.append("?");
			}
			List<NameValuePair> list = new ArrayList<>();

			Set<String> keySet = headers.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = headers.get(key);
				list.add(new BasicNameValuePair(key, value));
			}
			String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(list));
			paramsBuilder.append(paramsStr);
		}
		HttpGet httpGet = new HttpGet(paramsBuilder.toString());
		// 头
		if (headers != null && headers.keySet().isEmpty()) {
			Set<String> keySet = headers.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				String value = headers.get(key);
				httpGet.addHeader(key, value);
			}

		}
		return execute(httpGet);
	}

	/**
	 * 执行请求并返回string值
	 * 
	 * @param httpUriRequest
	 * @return
	 * @throws IOException
	 */
	private static String execute(HttpUriRequest httpUriRequest) throws IOException {
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			CloseableHttpResponse response = httpClient.execute(httpUriRequest);
			if (response.getStatusLine().getStatusCode() == 200) {// 请求成功状态
				try (BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()))) {
                     String result="";
                     String tmp=null;
                     while((tmp=bufferedReader.readLine())!=null){
                      result+=tmp;
                     }
					return result;
				}
			}
		}
		return null;
	}


}

 

地址:https://www.leftso.com/article/375.html

相关阅读

httpclient4.5使用详解 httpclient 4.5 post传递json参数
本文将展示如何使用“接受所有”SSL支持来配置Apache HttpClient 4。目标很简单 - 使用没有有效证书的HTTPS URL。
HttpClient的RestTemplate - Java配置示例
Apache HttpClient 4.x 使用详解
引言    modbus tcp通讯Java的方案之前已经讲解过一种,modbus4j实现Java语言的modbus tcp协议通讯
HttpClient Basic Authentication基本认证,本教程将说明如何在Apache HttpClient 4上配置基本身份验证。
在本教程中 - 我们将使用HttpClient 4进行POST - 首先使用授权,然后使用流畅的HttpClient API。最后 - 我们将讨论如何使用HttpClient上传文件。
modbus tcp 通讯协议在Java编程中的使用。本文主要讲解Java编程中通过modbus4j工具类来实现modbus tcp通讯协议的通讯。包括通过modbus协议读取数据,写入数据的实现。
HttpClient 4 按照POST重定向请求,本快速教程将展示如何配置Apache HttpClient 4以自动遵循POST请求的重定向。
Apache httpclient4.5 GET/POST/PUT/OPTION/DELETE工具类