import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.io.*; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.*; public class GjjHttpUtil {<!-- --> private static Logger log = LoggerFactory.getLogger(GjjHttpUtil.class); private final static String BOUNDARY = UUID.randomUUID().toString() .toLowerCase().replaceAll("-", "");// Boundary identification private final static String PREFIX = "--";// must exist private final static String LINE_END = "\r\\ "; /** * http Get request * * @param url * @param map * @return */ public static JSONObject httpGet(String url, Map<String, String> map) {<!-- --> JSONObject jsonResult = null; // Get the connection client tool CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try {<!-- --> URIBuilder uriBuilder = new URIBuilder(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (null != map) {<!-- --> for (String key : map.keySet()) {<!-- --> nvps.add(new BasicNameValuePair(key, map.get(key))); } } uriBuilder.setParameters(nvps); //Construct a GET request object based on the URI object with parameters HttpGet httpGet = new HttpGet(uriBuilder.build()); /* * Add request header information */ httpGet.addHeader("token", "9999"); //Execute the request response = httpClient.execute(httpGet); // Get the response entity object if (response.getStatusLine().getStatusCode() == 200) {<!-- --> HttpEntity entity = response.getEntity(); // Use the tool class provided by Apache to convert into a string String entityStr = EntityUtils.toString(entity, "UTF-8"); jsonResult = JSONObject.parseObject(entityStr); } else {<!-- --> jsonResult.put("msg", "Connection exception"); } } catch (ClientProtocolException e) {<!-- --> System.err.println("There is a problem with the HTTP protocol"); e.printStackTrace(); } catch (ParseException e) {<!-- --> System.err.println("Parse error"); e.printStackTrace(); } catch (URISyntaxException e) {<!-- --> System.err.println("URI parsing exception"); e.printStackTrace(); } catch (IOException e) {<!-- --> System.err.println("IO exception"); e.printStackTrace(); } finally {<!-- --> // Release the connection if (null != response) {<!-- --> try {<!-- --> response.close(); httpClient.close(); } catch (IOException e) {<!-- --> System.err.println("Error releasing connection"); e.printStackTrace(); } } } //Print response content System.out.println(jsonResult); return jsonResult; } /** * Post request * Send http protocol, pass parameters through post and return data **/ public static String httpPost(String urlStr, Map<String, String> params) {<!-- --> URL connect; StringBuffer data = new StringBuffer(); try {<!-- --> connect = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) connect.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false);//post cannot use cache connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect(); OutputStreamWriter paramout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); String paramsStr = ""; // Splice the parameters of the Post request for (String param : params.keySet()) {<!-- --> if (isNotBlank(params.get(param))) {<!-- --> paramsStr + = " & amp;" + param + "=" + URLEncoder.encode(params.get(param), "utf-8"); } } if (!paramsStr.isEmpty()) {<!-- --> paramsStr = paramsStr.substring(1); } System.out.println("====Capacity" + paramsStr.getBytes().length); paramout.write(paramsStr); paramout.flush(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = reader.readLine()) != null) {<!-- --> data.append(line); } paramout.close(); reader.close(); } catch (Exception e) {<!-- --> e.printStackTrace(); } return data.toString(); } private static boolean isNotBlank(String string) {<!-- --> return string != null & amp; & amp; !"".equals(string); } /** * POST Multipart Request * * @param requestUrl request url * @param requestText request parameters * @param requestFile Request to upload the file * @return * @throwsException * @Description: */ public static String sendRequest(String requestUrl, Map<String, String> requestText, Map<String, MultipartFile> requestFile) throws Exception {<!-- --> HttpURLConnection conn = null; InputStream input = null; OutputStream os = null; BufferedReader br = null; StringBuffer buffer = null; try {<!-- --> URL url = new URL(requestUrl); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setConnectTimeout(1000 * 10); conn.setReadTimeout(1000 * 10); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); conn.connect(); //Write content to the server, which is the parameters required to initiate an http request. os = new DataOutputStream(conn.getOutputStream()); //Request parameter part writeParams(requestText, os); //Request to upload file part writeFile(requestFile, os); // Request end flag String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END; os.write(endTarget.getBytes()); os.flush(); //Read the content returned by the server System.out.println("======================Response body================== ======="); System.out.println("ResponseCode:" + conn.getResponseCode() + ",ResponseMessage:" + conn.getResponseMessage()); if (conn.getResponseCode() == 200) {<!-- --> input = conn.getInputStream(); } else {<!-- --> input = conn.getErrorStream(); } br = new BufferedReader(new InputStreamReader(input, "UTF-8")); buffer = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) {<!-- --> buffer.append(line); } //...... System.out.println("Return message:" + buffer.toString()); } catch (Exception e) {<!-- --> log.error(e.getMessage(), e); throw new Exception(e); } finally {<!-- --> try {<!-- --> if (conn != null) {<!-- --> conn.disconnect(); conn = null; } if (os != null) {<!-- --> os.close(); os = null; } if (br != null) {<!-- --> br.close(); br = null; } } catch (IOException ex) {<!-- --> log.error(ex.getMessage(), ex); throw new Exception(ex); } } return buffer.toString(); } /** * Encode the post parameters and write them into the data stream * * @throwsException * @throwsIOException */ private static void writeParams(Map<String, String> requestText, OutputStream os) throws Exception {<!-- --> try {<!-- --> String msg = "Request parameter part:\\ "; if (requestText == null || requestText.isEmpty()) {<!-- --> msg + = "empty"; } else {<!-- --> StringBuilder requestParams = new StringBuilder(); Set<Map.Entry<String, String>> set = requestText.entrySet(); Iterator<Map.Entry<String, String>> it = set.iterator(); while (it.hasNext()) {<!-- --> Map.Entry<String, String> entry = it.next(); requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END); requestParams.append("Content-Disposition: form-data; name="") .append(entry.getKey()).append(""").append(LINE_END); requestParams.append("Content-Type: text/plain; charset=utf-8") .append(LINE_END); requestParams.append("Content-Transfer-Encoding: 8bit").append( LINE_END); requestParams.append(LINE_END);//After the parameter header is set, two line breaks are required, and then the parameter content is requestParams.append(entry.getValue()); requestParams.append(LINE_END); } os.write(requestParams.toString().getBytes()); os.flush(); msg + = requestParams.toString(); } //System.out.println(msg); } catch (Exception e) {<!-- --> log.error("writeParams failed", e); throw new Exception(e); } } /** * Encode the files uploaded by post and write them into the data stream * * @throwsIOException */ private static void writeFile(Map<String, MultipartFile> requestFile, OutputStream os) throws Exception {<!-- --> InputStream is = null; try {<!-- --> String msg = "Request to upload file part:\\ "; if (requestFile == null || requestFile.isEmpty()) {<!-- --> msg + = "empty"; } else {<!-- --> StringBuilder requestParams = new StringBuilder(); Set<Map.Entry<String, MultipartFile>> set = requestFile.entrySet(); Iterator<Map.Entry<String, MultipartFile>> it = set.iterator(); while (it.hasNext()) {<!-- --> Map.Entry<String, MultipartFile> entry = it.next(); if (entry.getValue() == null) {<!-- -->//Remove key-value pairs with empty value continue; } requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END); requestParams.append("Content-Disposition: form-data; name="") .append(entry.getKey()).append(""; filename="") .append(entry.getValue().getName()).append(""") .append(LINE_END); requestParams.append("Content-Type:") .append(entry.getValue().getContentType()) .append(LINE_END); requestParams.append("Content-Transfer-Encoding: 8bit").append( LINE_END); requestParams.append(LINE_END);//After the parameter header is set, two line breaks are required, and then the parameter content is os.write(requestParams.toString().getBytes()); os.write(entry.getValue().getBytes()); os.write(LINE_END.getBytes()); os.flush(); msg + = requestParams.toString(); } } //System.out.println(msg); } catch (Exception e) {<!-- --> log.error("writeFile failed", e); throw new Exception(e); } finally {<!-- --> try {<!-- --> if (is != null) {<!-- --> is.close(); } } catch (Exception e) {<!-- --> log.error("writeFile FileInputStream close failed", e); throw new Exception(e); } } } /** * ContentType (this part can be ignored, MultipartFile has corresponding methods to obtain) * * @param file * @return * @throwsIOException * @Description: */ public static String getContentType(MultipartFile file) throws Exception {<!-- --> String streamContentType = "application/octet-stream"; String imageContentType = ""; ImageInputStream image = null; try {<!-- --> image = ImageIO.createImageInputStream(file); if (image == null) {<!-- --> return streamContentType; } Iterator<ImageReader> it = ImageIO.getImageReaders(image); if (it.hasNext()) {<!-- --> imageContentType = "image/" + it.next().getFormatName(); return imageContentType; } } catch (IOException e) {<!-- --> log.error("method getContentType failed", e); throw new Exception(e); } finally {<!-- --> try {<!-- --> if (image != null) {<!-- --> image.close(); } } catch (IOException e) {<!-- --> log.error("ImageInputStream close failed", e); ; throw new Exception(e); } } return streamContentType; } // MockMultipartFile is a unit test class, so it requires a unit test package // ContentType is org.apache.http.entity.ContentType // ContentType.APPLICATION_OCTET_STREAM.toString() can be replaced by the string application/octet-stream public static void main(String[] args) throws Exception {<!-- --> /** * Method 1 can only be used for testing and cannot be used for formal packaging. */ // String requestURL = "http://127.0.0.1:8080/api/uploadFile"; // GjjHttpUtil httpReuqest = new GjjHttpUtil(); // // Map<String,String> requestText = new HashMap<>(); // requestText.put("token","123456"); //Parameters passed // Map<String,MultipartFile> requestFile = new HashMap<>(); // File file = new File("D:\save\provide\demo.png");//File // FileInputStream fileInputStream = new FileInputStream(file); // //Transfer files in a streaming manner. MockMultipartFile is for testing and will not be packaged during packaging. // MultipartFile multipartFile = new MockMultipartFile(file.getName(), // file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), // fileInputStream); // requestFile.put("image",multipartFile); // //Get the return value // String data = httpReuqest.sendRequest(requestURL, requestText, requestFile); /** *Method 2, can be used in formal environment */ //content is base64 //If you want to completely obtain a base64 test data, you can get it here https://www.sojson.com/image2base64.html String content = ""; String token = "123456"; String requestURL = "http://127.0.0.1:8080/api/uploadFile"; GjjHttpUtil httpReuqest = new GjjHttpUtil(); Map<String,String> requestText = new HashMap<>(); requestText.put("access_token",token); Map<String, MultipartFile> requestFile = new HashMap<>(); String fileName = Utils.buildMallOrderSn() + ".jpg"; MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(content); requestFile.put(fileName,multipartFile); String data = httpReuqest.sendRequest(requestURL, requestText, requestFile); /** * Case of multiple files */ //content is base64 //If you want to completely obtain a base64 test data, you can get it here https://www.sojson.com/image2base64.html String content = ""; List<String> str = new ArrayList<>(); str.add(content); str.add(content); str.add(content); String token = "123456"; String requestURL = "http://127.0.0.1:8080/api/uploadFile"; GjjHttpUtil httpReuqest = new GjjHttpUtil(); Map<String,String> requestText = new HashMap<>(); requestText.put("access_token",token); Map<String, MultipartFile> requestFile = new HashMap<>(); List<String> list = new ArrayList<>(); for(String con:str){<!-- --> // Randomly generate file name String fileName = Utils.buildMallOrderSn(); list.add(fileName); MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(con); requestFile.put(fileName,multipartFile); } //The name used to save the file, so that it can be easily obtained later based on the file name. requestText.put("imgNames",list.toString()); String data = httpReuqest.sendRequest(requestURL, requestText, requestFile); } }
BASE64DecodedMultipartFile class:
import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.*; public class BASE64DecodedMultipartFile implements MultipartFile {<!-- --> private final byte[] imgContent; private final String header; public BASE64DecodedMultipartFile(byte[] imgContent, String header) {<!-- --> this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() {<!-- --> return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() {<!-- --> return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() {<!-- --> return header.split(":")[1]; } @Override public boolean isEmpty() {<!-- --> return imgContent == null || imgContent.length == 0; } @Override public long getSize() {<!-- --> return imgContent.length; } @Override public byte[] getBytes() throws IOException {<!-- --> return imgContent; } @Override public InputStream getInputStream() throws IOException {<!-- --> return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException {<!-- --> new FileOutputStream(dest).write(imgContent); } public static MultipartFile base64ToMultipart(String base64) {<!-- --> try {<!-- --> String[] baseStrs = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStrs[1]); for (int i = 0; i < b.length; + + i) {<!-- --> if (b[i] < 0) {<!-- --> b[i] + = 256; } } return new BASE64DecodedMultipartFile(b, baseStrs[0]); } catch (IOException e) {<!-- --> e.printStackTrace(); return null; } } }
utils tool class
import java.text.SimpleDateFormat; import java.util.*; /** * Tools * @author zhn * */ public class Utils {<!-- --> private static final char[] digits = new char[]{<!-- -->'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', ' d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l\ ', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', ' C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K\ ', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; /** * Convert byte array into hexadecimal string * * @param bArray * @return */ public static String bytesToHexString(byte[] bArray) {<!-- --> StringBuffer sb = new StringBuffer(bArray.length); String sTemp; for (int i = 0; i < bArray.length; i + + ) {<!-- --> sTemp = Integer.toHexString(0xFF & amp; bArray[i]); if (sTemp.length() < 2) sb.append(0); sb.append(sTemp.toUpperCase()); } return sb.toString(); } /** * Convert string to byte array * * @param hex * @return */ public static byte[] hexStringToByte(String hex) {<!-- --> int len = (hex.length() / 2); byte[] result = new byte[len]; char[] achar = hex.toCharArray(); for (int i = 0; i < len; i + + ) {<!-- --> int pos = i * 2; result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1])); } return result; } /** *Convert string to hexadecimal string * * @param s * @return */ public static String stringToHexString(String s) {<!-- --> String str = ""; for (int i = 0; i < s.length(); i + + ) {<!-- --> int ch = (int) s.charAt(i); String s4 = Integer.toHexString(ch); str = str + s4; } return str; } private static byte toByte(char c) {<!-- --> byte b = (byte) "0123456789ABCDEF".indexOf(c); return b; } /** * appId + appkey + timestamp + nonce in ascending dictionary order * @param appId * @param appkey * @param timestamp * @param nonce * @return The string obtained by sorting and adding */ public static String sortData(String appId, String appkey, String timestamp, String nonce){<!-- --> List<String> list = new ArrayList<String>(); list.add(appId); list.add(appkey); list.add(timestamp); list.add(nonce); Collections.sort(list); String newStr = ""; for(int i = 0; i < list.size(); i + + ){<!-- --> newStr + = list.get(i); } return newStr; } // Randomly generate 16-digit string public static String getRandomStr() {<!-- --> String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 16; i + + ) {<!-- --> int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } /** * Randomly generate a string of dates plus letters * @return */ public static String buildMallOrderSn() {<!-- --> String dateStr = (new SimpleDateFormat("yyyyMMdd")).format(new Date()); StringBuffer shortBuffer = new StringBuffer(); String uuid = UUID.randomUUID().toString().replace("-", ""); for(int i = 0; i < 8; + + i) {<!-- --> String str = uuid.substring(i * 4, i * 4 + 4); int x = Integer.parseInt(str, 16); shortBuffer.append(digits[x % 62]); } return dateStr + shortBuffer.toString(); } }
The interface obtains the file stream file passed by the above interface
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @RequestMapping("/test") //Cross-domain annotations @CrossOrigin public class demo {<!-- --> /** * Receive stream information * * @param request * @return */ @PostMapping("/receiveStream") public String receiveStream(HttpServletRequest request) {<!-- --> //Parameter one String materialsName = request.getParameter("access_token"); //Parameter one String code = request.getParameter("imgNames"); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //The element whose key is File in the request (i.e. file element) List<MultipartFile> list = multiRequest.getFiles("img"); MultipartFile file = list.get(0); System.out.println(code); System.out.println(materialsName); return null; } }
Reference link