IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> http请求工具类,实现multipart/form-data的文档上传,对于https协议跳过证书验证 -> 正文阅读

[网络协议]http请求工具类,实现multipart/form-data的文档上传,对于https协议跳过证书验证

LoadRunner11目前仅支持jdk 1.6版本,在压测时,使用高版本的jdk生成的工具类调用会报错,jdk 1.6来开发调用http协议的工具类,工具使用Apache的httpclient实现,具体步骤如下,在这里下载源码

1、pom引用

    <dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>httpclient</artifactId>
	    <version>4.5.13</version>
  	</dependency>
	<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>httpcore</artifactId>
	    <version>4.4.14</version>
	</dependency>
	<dependency>
		<groupId>net.sf.json-lib</groupId>
		<artifactId>json-lib</artifactId>
		<classifier>jdk15</classifier>
		<version>2.4</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
	<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>httpmime</artifactId>
	    <version>4.5.13</version>
	</dependency>

2、Content-Type为multipart/form-data的POST请求工具类实现,并支持文件上传,代码如下

private static final Integer CONNECT_TIMEOUT = 15000;
private static final Integer REND_TIMEOUT = 60000;
/**
	 * 使用httpClient发送post请求,contentType 类型为application/x-www-form-urlencoded
	 * @param httpurl	请求的url
	 * @param params	请求的参数
	 * @param headers	请求头
	 * @param filePathMap	上传文件
	 * @return
	 * @throws Exception
	 */
	public static EdsmHttpResponse sendPostFormRequst(String httpurl, Map<String, Object> params,
			Map<String, Object> headers, Map<String, String> filePathMap) throws Exception {
		EdsmHttpResponse resultResponse = null;
		CloseableHttpClient httpClient = createSSLClientDefault(httpurl);
		// 创建Post请求
		HttpPost httpPost = new HttpPost(httpurl);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		String boundary = "DSPSBoundary" + System.currentTimeMillis();
		builder.setBoundary(boundary);
		httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
		// 设置其他自定义 headers
		if (headers != null && !headers.isEmpty()) {
			for (Map.Entry<String, Object> header : headers.entrySet()) {
				httpPost.setHeader(header.getKey(), header.getValue().toString());
			}
		}
		//设置参数
		if (params != null && !params.isEmpty()) {
			Set<String> keySet = params.keySet();
			Iterator<String> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				Object value = params.get(key);
				builder.addTextBody(key, (String) value,ContentType.create("text/plain", Consts.UTF_8));
			}
		}
		//添加文件
		if ((filePathMap != null) && (!filePathMap.isEmpty())) {
			for (Map.Entry<String, String> filePath : filePathMap.entrySet()) {
				File file = new File(filePath.getValue());
				if(file.exists()) {
					FileBody bin = new FileBody(file);
					builder.addPart(filePath.getKey(),bin);
				}
			}
		}
		HttpEntity multipart = builder.build();
		
		httpPost.setEntity(multipart);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
				.setSocketTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REND_TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			String result = "";
			if (statusCode != 200) {
			}
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity, "UTF-8");
			}
			resultResponse = new EdsmHttpResponse(statusCode, result);
			return resultResponse;
		} catch (ClientProtocolException e) {
			throw new Exception("ClientProtocolException", e);
		} catch (ParseException e) {
			throw new Exception("ParseException", e);
		} catch (ConnectException e) {
			throw new Exception("ConnectException", e);
		} catch (SocketTimeoutException e) {
			throw new Exception("SocketTimeoutException", e);
		} catch (IOException e) {
			throw new Exception("IOException", e);
		} finally {
			try {
				// 释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
			}
		}
	}

3、Content-Type为multipart/form-data的GET请求工具类实现,代码如下

/**
	 * 发送GET请求
	 * 
	 * @param httpurl    请求的部分url
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static EdsmHttpResponse sendGetRequst(String httpurl, Map<String, String> map) throws Exception {
		EdsmHttpResponse resultResponse = null;
		CloseableHttpClient httpClient = createSSLClientDefault(httpurl);
		StringBuffer sb = new StringBuffer();
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		for (Entry<String, String> entry : map.entrySet()) {
			parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		String str = EntityUtils.toString(new UrlEncodedFormEntity(parameters, "utf-8"));
		sb.append(httpurl);
		sb.append("?");
		sb.append(str);
		// 创建Get请求
		HttpGet httpGet = new HttpGet(sb.toString());
		String boundary = "DSPSBoundary" + System.currentTimeMillis();
		httpGet.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
				.setSocketTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REND_TIMEOUT).build();
		httpGet.setConfig(requestConfig);
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)GET请求
			response = httpClient.execute(httpGet);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			String result = "";
			if (statusCode != 200) {
			}
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity, "UTF-8");
			}
			resultResponse = new EdsmHttpResponse(statusCode, result);
			return resultResponse;
		} catch (ClientProtocolException e) {
			throw new Exception("ClientProtocolException", e);
		} catch (ParseException e) {
			throw new Exception("ParseException", e);
		} catch (ConnectException e) {
			throw new Exception("ConnectException", e);
		} catch (SocketTimeoutException e) {
			throw new Exception("SocketTimeoutException", e);
		} catch (IOException e) {
			throw new Exception("IOException", e);
		} finally {
			// 释放资源
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
				}
			}
		}
	}

4、Content-Type为application/json的POST请求工具类实现,代码如下

/**
	 * 使用httpClient发送数据类型application/json的post请求
	 * 
	 * @param httpurl 请求地址
	 * @param params  请求参数
	 * @param headers 请求头
	 * @return
	 * @throws Exception
	 */
	public static EdsmHttpResponse sendPostJsonRequst(String httpurl, Map<String, Object> params,
			Map<String, Object> headers) throws Exception {
		EdsmHttpResponse resultResponse = null;
		CloseableHttpClient httpClient = createSSLClientDefault(httpurl);
		// 创建Post请求
		HttpPost httpPost = new HttpPost(httpurl);
		if (params != null && !params.isEmpty()) {
			// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
			JSONObject fromObject = JSONObject.fromObject(params);
			httpPost.setEntity(new StringEntity(fromObject.toString(), "UTF-8"));
		}
		httpPost.setHeader("Content-Type", "application/json");
		// 设置其他自定义 headers
		if (headers != null && !headers.isEmpty()) {
			for (Map.Entry<String, Object> header : headers.entrySet()) {
				httpPost.setHeader(header.getKey(), header.getValue().toString());
			}
		}
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
				.setSocketTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REND_TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			String result = "";
			if (statusCode != 200) {
			}
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity, "UTF-8");
			}
			resultResponse = new EdsmHttpResponse(statusCode, result);
			return resultResponse;
		} catch (ClientProtocolException e) {
			throw new Exception("ClientProtocolException", e);
		} catch (ParseException e) {
			throw new Exception("ParseException", e);
		} catch (ConnectException e) {
			throw new Exception("ConnectException", e);
		} catch (SocketTimeoutException e) {
			throw new Exception("SocketTimeoutException", e);
		} catch (IOException e) {
			throw new Exception("IOException", e);
		} finally {
			try {
				// 释放资源
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
			}
		}
	}

5、对于HTTPS协议,跳过客户端证书的验证,具体实现如下

/**
	 * 创建默认的http链接
	 * @param httpurl	请求的url
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault(String httpurl) {
		if (StringUtils.isNotBlank(httpurl)) {
			String srt = httpurl.substring(0, 5);
    		if("https".equalsIgnoreCase(srt)) {
    			try {
    				// 使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
    				SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    					// 信任所有
    					public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    						return true;
    					}
    				}).build();
    				// 有效的SSL会话并匹配到目标主机。
    				HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    				return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    			} catch (KeyManagementException e) {
    				e.printStackTrace();
    			} catch (NoSuchAlgorithmException e) {
    				e.printStackTrace();
    			} catch (KeyStoreException e) {
    				e.printStackTrace();
    			}
    		}
		}
		return HttpClients.createDefault();

	}

5、调用方法如下

public static void main(String[] args) {
		String url = "";//请求的URL
		Map<String, Object> params = new HashMap<String, Object>();//传参
		Map<String, Object> headers = new HashMap<String, Object>();//请求头
		Map<String, String> filePathMap = new HashMap<String, String>();//需要上传的文件
		try {
			//发起application/x-www-form-urlencoded的post请求工具类
			RestfulHttpUtil.sendPostFormRequst(url, params, headers, filePathMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			//发起application/json的post请求
			RestfulHttpUtil.sendPostJsonRequst(url, params, headers);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Map<String, String> map = new HashMap<String, String>();//的参数
		try {
			//发起multipart/form-data; 的get请求
			RestfulHttpUtil.sendGetRequst(url, map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

对于未实现的Content-Type为application/json的GET请求,可以仿照multipart/form-data的GET进行实现。

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-12-01 18:03:38  更:2021-12-01 18:05:04 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/6 8:48:07-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码