使用http request
Multipart/Form-Data Encoding
Multipart/form-data is designed for POST requests that combine both binary (e.g., files) and character data (e.g., parameters).编码涉及将请求主体划分为多个部分,每个部分都以边界字符串。args)抛出异常{ 字符串url =“ http://example.com/upload”; 字符串param =“ value”; 文件textfile = new file(“/path/to/file.txt”); 文件binaryfile =新文件(“/path/to/file.bin”); 字符串边界= long.tohexstring(system.currentTimeMillis()); urlConnection Connection = new URL(url).openconnection(); connection.setDoOutput(true); connection.setRequestProperty(“ content-type”,“多部分/form-data; boundare =” boundare); 尝试(outputStream输出= Connection.getOutputStream(); printwriter writer = new printwriter(new UppoteStreamWriter(output,standardcharsets.utf_8),true)){ //发送参数 writer.append(“ - ”边界).append(“ \ r \ n”); writer.append(“ content-disposition:form-data; name = \“ param \”“)。append(“ \ r \ n”); writer.append(“ content-type:text/plain; charset =“ standardcharsets.utf_8).append(“ \ r \ n”); writer.append(“ \ r \ n”)。append(param).append(“ \ r \ n”)。flush(); //发送文本文件 writer.append(“ - ”边界).append(“ \ r \ n”); writer.append(“ content-disposition:form-data; name = \“ textfile \”; filename = \“” textfile.getName()“ \”“)。append(“ \ r \ n”); writer.append(“ content-type:text/plain; charset =“ standardcharsets.utf_8).append(“ \ r \ n”); writer.append(“ \ r \ n”)。flush(); files.copy(textfile.topath(),输出); output.flush(); writer.append(“ \ r \ n”)。flush(); //发送二进制文件 writer.append(“ - ”边界).append(“ \ r \ n”); writer.append(“ content-disposition:form-data; name = \“ binaryfile \”; filename = \“” binaryfile.getName()“ \”“)。append(“ \ r \ n”); writer.append(“ content-type:” urlConnection.guessContentTypefromName(binaryfile.getName()))。append(“ \ r \ n”); writer.append(“ content-transfer-insoding:binary”)。append(“ \ r \ n”); writer.append(“ \ r \ n”)。flush(); files.copy(binaryfile.topath(),输出); output.flush(); writer.append(“ \ r \ n”)。flush(); //多部分/form-data的结尾 writer.append(“ - ”边界“ - ”)。append(“ \ r \ n”)。flush(); } int响应=((httpurlConnection)连接).getResponsecode(); system.out.println(“响应代码:” wonsectecode); } }
Additional NotesApache Commons FileUpload is only required on the server-side for handling uploaded files.
java.net.URLConnection is preferred for firing HTTP requests without external dependencies.For more information,请参阅java.net.urlconnection和multipart/form-data(rfc2388)上的文档。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3