• restFul风格调用get、post请求(包含文件上传与下载)


    httpUtil使用说明

    0,引用包

    package com.activeclub.utils;
    
    import com.activeclub.bean.dto.RequestDto;
    import com.activeclub.bean.entity.KeyValue;
    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    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.utils.URIBuilder;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.ssl.SSLContexts;
    import org.apache.http.ssl.TrustStrategy;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.StringUtils;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.net.ssl.SSLContext;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URI;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.List;
    

    1,get请求调用

    
    	/**
    	 * get请求
    	 *
    	 * @param requestDto      输入参数
    	 * @param servletResponse 反馈响应(用于文件下载)
    	 * @return 文本输出
    	 */
    	public static String doGet(RequestDto requestDto, HttpServletResponse servletResponse) {
    		String url = requestDto.getUrl();//请求的url路径
    		String jsonStr = requestDto.getJsonStr();//请求的json输入
    		List<KeyValue> params = requestDto.getParams();//请求的参数输入
    		List<KeyValue> headers = requestDto.getHeaders();//header参数
    		Boolean hasServletResponse = requestDto.getHasServletResponse();//反馈响应
    
    		// 中间变量
    		String resultString = "";
    		CloseableHttpClient httpclient = null;
    		CloseableHttpResponse response = null;
    		InputStream is = null;
    		OutputStream os = null;
    
    		try {
    
    			// 1 判断url的类型
    			if (url.startsWith("https")) {
    				httpclient = getIgnoeSSLClient();
    			} else {
    				httpclient = HttpClients.createDefault();
    			}
    
    			// 2 创建uri
    			URIBuilder builder = new URIBuilder(url);
    			if (params != null) {
    				for (KeyValue kv : params) {
    					builder.addParameter(kv.getKey(), kv.getValue().toString());
    				}
    			}
    			URI uri = builder.build();
    
    			// 3 创建http GET请求 并且 设置token
    			HttpGet httpGet = new HttpGet(uri);
    			if (headers != null) {
    				for (KeyValue kv : headers) {
    					httpGet.setHeader(kv.getKey(), kv.getValue().toString());
    				}
    			}
    
    			// 4 执行请求
    			response = httpclient.execute(httpGet);
    
    			// 5 直接进行转换
    			if (hasServletResponse) {// 5.1 有文件下载
    				for (Header header : response.getAllHeaders()) {
    					servletResponse.addHeader(header.getName(), header.getValue());
    				}
    
    				byte[] respStr = EntityUtils.toByteArray(response.getEntity());
    				is = new ByteArrayInputStream(respStr);
    				os = servletResponse.getOutputStream();
    				byte[] buffer = new byte[1024 * 1024];
    				int count = 0;
    				while ((count = is.read(buffer)) != -1) {
    					os.write(buffer, 0, count);
    				}
    				os.flush();
    
    			} else {// 5.2 没有有文件下载
    				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
    			}
    
    			if (url.startsWith("https")) {
    				EntityUtils.consume(response.getEntity());
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			// 关闭服务
    			if (response != null) {
    				try {
    					response.close();
    				} catch (IOException e) {
    					logger.error("CloseableHttpResponse close happend a error! ", e);
    				}
    			}
    			if (httpclient != null) {
    				try {
    					httpclient.close();
    				} catch (IOException e) {
    					logger.error("httpclient close happend a error! ", e);
    				}
    			}
    			if (is != null) {
    				try {
    					is.close();
    				} catch (IOException e) {
    					logger.error("InputStream close happend a error! ", e);
    				}
    			}
    			if (os != null) {
    				try {
    					os.close();
    				} catch (IOException e) {
    					logger.error("OutputStream close happend a error! ", e);
    				}
    			}
    		}
    		return resultString;
    	}
    

    2,post请求调用

    	/**
    	 * post请求
    	 *
    	 * @param requestDto      输入参数
    	 * @param multipartFile   上传文件
    	 * @param servletResponse 反馈响应(用于文件下载)
    	 * @return 文本输出
    	 */
    	public static String doPost(RequestDto requestDto, MultipartFile multipartFile, HttpServletResponse servletResponse) {
    		String url = requestDto.getUrl();//请求的url路径
    		String jsonStr = requestDto.getJsonStr();//请求的json输入
    		List<KeyValue> params = requestDto.getParams();//请求的参数输入
    		List<KeyValue> headers = requestDto.getHeaders();//header参数
    		Boolean hasServletResponse = requestDto.getHasServletResponse();//反馈响应
    
    		// 中间变量
    		File localFile = null;
    		CloseableHttpClient httpClient = null;
    		CloseableHttpResponse response = null;
    		InputStream is = null;
    		OutputStream os = null;
    		String resultString = "";
    
    		try {
    
    			// 1 创建Httpclient对象
    			if (url.startsWith("https")) {
    				httpClient = getIgnoeSSLClient();
    			} else {
    				httpClient = HttpClients.createDefault();
    			}
    
    			// 2 创建uri
    			URIBuilder builder = new URIBuilder(url);
    			if (params != null) {
    				for (KeyValue kv : params) {
    					builder.addParameter(kv.getKey(), kv.getValue().toString());
    				}
    			}
    			URI uri = builder.build();
    
    			// 3 创建Http Post请求
    			HttpPost httpPost = new HttpPost(uri);
    			if (headers != null) {
    				for (KeyValue kv : headers) {
    					httpPost.addHeader(kv.getKey(), kv.getValue().toString());
    				}
    			}
    
    			if (!StringUtils.isEmpty(jsonStr)) {// 设置jsonBody
    				StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
    				httpPost.setEntity(entity);
    			}
    
    			// 4 创建请求内容[如果有文件上传]
    			if (null != multipartFile) {
    				localFile = multipartFileToFile(multipartFile);// 把文件转换成流对象FileBody
    				FileBody fileBody = new FileBody(localFile);
    				// 以浏览器兼容模式运行,防止文件名乱码。
    				MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
    				builder2.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    				builder2.addPart("file", fileBody);
    				HttpEntity entity = builder2.build();
    				httpPost.setEntity(entity);
    			}
    
    			// 5 执行http请求
    			response = httpClient.execute(httpPost);
    			if (hasServletResponse) {// 5.1 有文件下载
    				for (Header header : response.getAllHeaders()) {
    					servletResponse.addHeader(header.getName(), header.getValue());
    				}
    				byte[] respStr = EntityUtils.toByteArray(response.getEntity());
    				is = new ByteArrayInputStream(respStr);
    				os = servletResponse.getOutputStream();
    				byte[] buffer = new byte[1024 * 1024];
    				int count = 0;
    				while ((count = is.read(buffer)) != -1) {
    					os.write(buffer, 0, count);
    				}
    				os.flush();
    			} else {
    				resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    			}
    			// https结束
    			if (url.startsWith("https")) {
    				EntityUtils.consume(response.getEntity());
    			}
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			// 关闭服务
    			if (response != null) {
    				try {
    					response.close();
    				} catch (IOException e) {
    					logger.error("response close happend a error! ", e);
    				}
    			}
    			if (httpClient != null) {
    				try {
    					httpClient.close();
    				} catch (IOException e) {
    					logger.error("httpClient close happend a error! ", e);
    				}
    			}
    			if (localFile != null) {
    				try {
    					localFile.delete();
    				} catch (Exception e) {
    					logger.error("localFile close happend a error! ", e);
    				}
    			}
    			if (is != null) {
    				try {
    					is.close();
    				} catch (IOException e) {
    					logger.error("inputStream close happend a error! ", e);
    				}
    			}
    			if (os != null) {
    				try {
    					os.close();
    				} catch (IOException e) {
    					logger.error("outputStream close happend a error! ", e);
    				}
    			}
    		}
    		return resultString;
    	}
    

    3,辅助函数

    	// https 操作
    	private static CloseableHttpClient getIgnoeSSLClient() throws Exception {
    		SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
    			@Override
    			public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    				return true;
    			}
    		}).build();
    		CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
    				setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    		return client;
    	}
    
    	// MultipartFile 转换成为File (需要手动删除delete)
    	private static File multipartFileToFile(MultipartFile multiFile) {
    		// 获取文件名
    		String fileName = multiFile.getOriginalFilename();
    
    		try {
    			String path = System.getProperty("user.dir");
    
    			fileName = URLDecoder.decode(fileName, "utf-8");
    			fileName = URLEncoder.encode(fileName, "utf-8");
    
    			File file = new File(path + "\" + fileName);
    			file.createNewFile();
    			multiFile.transferTo(file);
    			return file;
    		} catch (Exception e) {
    			logger.error("file transfer error:", e);
    		}
    		return null;
    	}
    

    4,测试main函数

    	public static void main(String[] args) {
    		/**
    		 *1,无入参的get请求(成功)
    		 */
    		RequestDto requestDto = new RequestDto();
    		requestDto.setUrl("https://a1.cnblogs.com/group/B1");
    		String result1 = doGet(requestDto, null);
    		System.out.println(result1);
    		System.out.println("--------------------------");
    
    		/**
    		 *2,有入参的get请求(成功)
    		 */
    		RequestDto requestDto2 = new RequestDto();
    		requestDto2.setUrl("https://www.cnblogs.com/ajax/wechatshare/getconfig");
    		requestDto2.addParam("url","https%3A%2F%2Fwww.cnblogs.com%2F&file");
    		String result2 = doGet(requestDto2, null);
    		System.out.println(result2);
    		System.out.println("--------------------------");
    
    		/**
    		 *3,无入参的post请求
    		 */
    		RequestDto requestDto3 = new RequestDto();
    		requestDto3.setUrl("https://www.cnblogs.com/aggsite/editorpickstat");
    		String result3 = doPost(requestDto3, null,null);
    		System.out.println(result3);
    		System.out.println("--------------------------");
    
    		/**
    		 *4,有json参数的post请求
    		 */
    		RequestDto requestDto4 = new RequestDto();
    		requestDto4.setUrl("https://recomm.cnblogs.com/api/v2/recomm/blogpost/reco");
    		requestDto4.setJsonStr("{"itemId":11420047,"itemTitle":"\n    知识点复习统计\n    \n\n\n"}");
    		String result4 = doPost(requestDto4, null,null);
    		System.out.println(result4);
    		System.out.println("--------------------------");
    
    	}
    

    5,其他

    可直接访问github https://github.com/mufasa007/repository
    其中的app-framework-utils里面的HttpUtil函数

  • 相关阅读:
    顺序表的C语言实现
    Nginx模块开发(5)————开发简单的HTTP过滤模块
    python集合(set)
    python——封装、解构
    python——杨辉三角
    python——bytes、bytearray
    python算法——求10万以内的质数
    python算法——打印菱形、对等三角、闪电
    python字符串操作
    python—冒泡排序
  • 原文地址:https://www.cnblogs.com/Mufasa/p/14136816.html
Copyright © 2020-2023  润新知