这里做个记录,通过此次问题的解决,弄清POST同时传文件及参数时,底层到底是怎么组成,文件流及参数是怎么分隔组成,及分隔符如何写入流。
好,废话不多说,直接上代码,此代码配置好自己参数可直接调试,无需引入更多包。
1 package com.hhb; 2 import java.io.*; 3 import java.net.HttpURLConnection; 4 import java.net.URL; 5 import java.net.URLConnection; 6 public class upoad { 7 public static void main(String[] args) { 8 System.out.println("上传开始"); 9 //要上传的图片 10 String uploadFilePaths = "D:\\loadFile.jpg"; 11 //请求上传图片API地址 12 String actionUrl = "https://localhost/api/File/UploadFile"; 13 14 //参数 Rax 随机数(10位数)。TimeUtc 时间戳(秒级别) 15 String Scope = "TrackReceipt"; 16 String Rax = "5tqczr48id"; 17 String TimeUtc = "1677722176"; 18 String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3ByaW1hcnlzaWQiOiIzYTA5YjIxMC04OGE3LWE4MDItY2Y1Mi1iOGI2YzhjNDE1OTMiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiIwOGRhZjgyYy01M2Q4LTQxZTQtODAzOC1kMmUyMDkyMmNhM2MiLCJuYmYiOjE2Nzc3MTk3NDQsImV4cCI6MTY4MDMxMTc0NCwiaXNzIjoib2NlbG90IiwiYXVkIjoiaGNkIn0.erl5opo0tie-MVmEMQYYoaGkIs-LbbftYREoHAfyzJg"; 19 //调用 20 String rel = uploadFile(actionUrl, uploadFilePaths, Scope, Rax, TimeUtc, token); 21 System.out.println("返回结果:" + rel); 22 } 23 24 /** 25 * 多文件上传的方法 26 * 27 * @param actionUrl:上传的路径 28 * @param uploadFilePaths:需要上传的文件路径,数组 29 * @return 30 */ 31 @SuppressWarnings("finally") 32 public static String uploadFile(String actionUrl, String uploadFilePaths, String Scope 33 , String Rax, String TimeUtc, String token) { 34 String end = "\r\n"; 35 String twoHyphens = "--"; 36 String boundary = "*****"; 37 38 DataOutputStream ds = null; 39 InputStream inputStream = null; 40 InputStreamReader inputStreamReader = null; 41 BufferedReader reader = null; 42 StringBuffer resultBuffer = new StringBuffer(); 43 String tempLine = null; 44 token = "Bearer " + token; 45 46 String uploadFile = uploadFilePaths; 47 String filename = uploadFile.substring(uploadFile.lastIndexOf("\\") + 1); 48 49 try { 50 // 统一资源 51 URL url = new URL(actionUrl); 52 // 连接类的父类,抽象类 53 URLConnection urlConnection = url.openConnection(); 54 // http的连接类 55 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; 56 // 设置是否从httpUrlConnection读入,默认情况下是true; 57 httpURLConnection.setDoInput(true); 58 // 设置是否向httpUrlConnection输出 59 httpURLConnection.setDoOutput(true); 60 // Post 请求不能使用缓存 61 httpURLConnection.setUseCaches(false); 62 // 设定请求的方法,默认是GET 63 httpURLConnection.setRequestMethod("POST"); 64 // 设置字符编码连接参数 65 httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); 66 // 设置字符编码 67 httpURLConnection.setRequestProperty("Charset", "UTF-8"); 68 // 设置请求内容类型 69 httpURLConnection.setRequestProperty("Authorization", token); 70 71 httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 72 73 // 设置DataOutputStream 74 ds = new DataOutputStream(httpURLConnection.getOutputStream()); 75 76 //封装键值对数据一 77 ds.writeBytes(twoHyphens + boundary + end); 78 ds.writeBytes("Content-Disposition: form-data; name=\"" + "Scope" + "\""); 79 ds.writeBytes(end); 80 // ds.writeBytes("Content-Type: " + "text/plain"); 81 // ds.writeBytes(end); 82 // ds.writeBytes("Content-Lenght: " + ("" + Scope).length()); 83 // ds.writeBytes(end); 84 ds.writeBytes(end); 85 ds.writeBytes("" + Scope); 86 ds.writeBytes(end); 87 88 89 //封装键值对数据三 90 ds.writeBytes(twoHyphens + boundary + end); 91 ds.writeBytes("Content-Disposition: form-data; name=\"" + "Rax" + "\""); 92 ds.writeBytes(end); 93 ds.writeBytes(end); 94 ds.writeBytes("" + Rax); 95 ds.writeBytes(end); 96 97 //封装键值对数据四 98 ds.writeBytes(twoHyphens + boundary + end); 99 ds.writeBytes("Content-Disposition: form-data; name=\"" + "TimeUtc" + "\""); 100 ds.writeBytes(end); 101 ds.writeBytes(end); 102 ds.writeBytes("" + TimeUtc); 103 ds.writeBytes(end); 104 105 //封装图片数据 106 ds.writeBytes(twoHyphens + boundary + end); 107 ds.writeBytes("Content-Disposition: form-data; " + "name=\"File\";filename=\"" + filename 108 + "\"" + end); 109 ds.writeBytes("Content-Type: " + "image/jpeg" + end); 110 //ds.writeBytes("Content-Lenght: "+file.length()+ end); 111 ds.writeBytes(end); 112 FileInputStream fStream = new FileInputStream(uploadFile); 113 int bufferSize = 1024; 114 byte[] buffer = new byte[bufferSize]; 115 int length = -1; 116 while ((length = fStream.read(buffer)) != -1) { 117 ds.write(buffer, 0, length); 118 } 119 ds.writeBytes(end); 120 /* close streams */ 121 fStream.close(); 122 //输入结束 123 ds.writeBytes(twoHyphens + boundary + twoHyphens + end); 124 /* close streams */ 125 ds.flush(); 126 if (httpURLConnection.getResponseCode() >= 300) { 127 throw new Exception( 128 "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode()); 129 } 130 if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 131 inputStream = httpURLConnection.getInputStream(); 132 inputStreamReader = new InputStreamReader(inputStream); 133 reader = new BufferedReader(inputStreamReader); 134 tempLine = null; 135 resultBuffer = new StringBuffer(); 136 while ((tempLine = reader.readLine()) != null) { 137 resultBuffer.append(tempLine); 138 resultBuffer.append("\n"); 139 } 140 } 141 } catch (Exception e) { 142 e.printStackTrace(); 143 } finally { 144 if (ds != null) { 145 try { 146 ds.close(); 147 } catch (IOException e) { 148 // TODO Auto-generated catch block 149 e.printStackTrace(); 150 } 151 } 152 if (reader != null) { 153 try { 154 reader.close(); 155 } catch (IOException e) { 156 // TODO Auto-generated catch block 157 e.printStackTrace(); 158 } 159 } 160 if (inputStreamReader != null) { 161 try { 162 inputStreamReader.close(); 163 } catch (IOException e) { 164 // TODO Auto-generated catch block 165 e.printStackTrace(); 166 } 167 } 168 if (inputStream != null) { 169 try { 170 inputStream.close(); 171 } catch (IOException e) { 172 // TODO Auto-generated catch block 173 e.printStackTrace(); 174 } 175 } 176 return resultBuffer.toString(); 177 } 178 } 179 }
参考:http://www.manongjc.com/detail/26-ibpgtovosforqma.html标签:end,String,form,Java,writeBytes,null,data,ds,httpURLConnection From: https://www.cnblogs.com/tjdk/p/17172258.html
https://blog.csdn.net/AP0906424/article/details/108998071