博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How to upload a file via a HTTP multipart request in Java without using any external libraries
阅读量:5033 次
发布时间:2019-06-12

本文共 5921 字,大约阅读时间需要 19 分钟。

 

There was this situation when there was a need for my applet to send some log files (generated by some desktop application) on the remote clients.

To keep my applet lean, I chose to implement this file upload function by sending a HTTP multipart request when my applet loads on the remote client’s browser. Policies were in place to ensure that my applet was able to read the log files and send them back to a web server which will collect the log files.

This post documents how I can upload a file by sending a HTTP multipart request in Java without using any external libraries. For the sake of brevity, I used the  to accept the file from the codes that will be mentioned in this post.

Having an idea of what the HTTP multipart request will look like

One way to know how a HTTP multipart request will look like will be to capture the HTTP multipart request that browsers send web servers. To instruct my browser to show me how my Java program should send the HTTP multipart request, I first create the following HTML code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<
html
>
<
body
>
<
form
action
=
"http://ipv4.fiddler/test/GetPostRequest.php"
method
=
"post"
enctype
=
"multipart/form-data"
>
<
p
>
<
strong
>My file description:</
strong
>
<
textarea
name
=
"myFileDescription"
rows
=
"2"
cols
=
"20"
>
</
textarea
><
br
/> <
br
/>
<
strong
>My file:</
strong
><
br
/>
<
input
type
=
"file"
name
=
"myFile"
>
</
p
>
<
input
type
=
"submit"
value
=
"Submit"
>
</
form
>
</
body
>
</
html
>

And then point my browser to the HTML file. I then use the HTML form to upload a file and have  examine the HTTP multipart request.

Fiddler showed me the following:

POST http://127.0.0.1/GetPostRequest.php HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive Referer: http://localhost/GetPostRequest.php Content-Length: 864 Cache-Control: max-age=0 Origin: http://localhost User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.91 Safari/534.30 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryX6nBO7q27yQ1JNbb Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 ------WebKitFormBoundaryX6nBO7q27yQ1JNbb Content-Disposition: form-data; name="myFileDescription" Log file for 20150208. ------WebKitFormBoundaryX6nBO7q27yQ1JNbb Content-Disposition: form-data; name="myFile"; filename="20150208.log" Content-Type: text/plainfile contents... ------WebKitFormBoundaryX6nBO7q27yQ1JNbb--

Constructing a HTTP multipart request to upload the file to the web server endpoint

With the output from Fiddler, sending the HTTP multipart request with my Java program is straightforward. To avoid using external libraries, I use the following classes provided by the Java standard library:

  • java.io.BufferedReaderjava.io.BufferedWriterjava.io.Filejava.io.FileInputStreamjava.io.InputStreamReaderjava.io.OutputStreamjava.io.OutputStreamWriterjava.net.HttpURLConnectionjava.net.URL

      

And wrote the following codes to upload my log file to my web server endpoint with a HTTP multipart request.

// Connect to the web server endpointURL serverUrl =    new URL("http://localhost/test/GetPostRequest.php");HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection(); String boundaryString = "----SomeRandomText";String fileUrl = "/logs/20150208.log";File logFileToUpload = new File(fileUrl); // Indicate that we want to write to the HTTP request bodyurlConnection.setDoOutput(true);urlConnection.setRequestMethod("POST");urlConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString); // Indicate that we want to write some data as the HTTP request bodyurlConnection.setDoOutput(true); OutputStream outputStreamToRequestBody = urlConnection.getOutputStream();BufferedWriter httpRequestBodyWriter =    new BufferedWriter(new OutputStreamWriter(outputStreamToRequestBody)); // Include value from the myFileDescription text area in the post datahttpRequestBodyWriter.write("\n--" + boundaryString + "\n");httpRequestBodyWriter.write("Content-Disposition: form-data; name=\"myFileDescription\"");httpRequestBodyWriter.write("\n\n");httpRequestBodyWriter.write("Log file for 20150208"); // Include the section to describe the filehttpRequestBodyWriter.write("\n--" + boundaryString + "\n");httpRequestBodyWriter.write("Content-Disposition: form-data;"        + "name=\"myFile\";"        + "filename=\""+ logFileToUpload.getName() +"\""        + "\nContent-Type: text/plain\n\n");httpRequestBodyWriter.flush(); // Write the actual file contentsFileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload); int bytesRead;byte[] dataBuffer = new byte[1024];while((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1) {    outputStreamToRequestBody.write(dataBuffer, 0, bytesRead);} outputStreamToRequestBody.flush(); // Mark the end of the multipart http requesthttpRequestBodyWriter.write("\n--" + boundaryString + "--\n");httpRequestBodyWriter.flush(); // Close the streamsoutputStreamToRequestBody.close();httpRequestBodyWriter.close();

  

Getting the HTTP response from the web server

After writing the payload for the HTTP multipart request to the output stream of the HttpURLConnection object, I would then read the response from my web server endpoint.

By using the HttpURLConnection object to read the HTTP response, I also trigger the actual uploading of the log file via a HTTP multipart request to the web server.

// Read response from web server, which will trigger the multipart HTTP request to be sent.BufferedReader httpResponseReader =    new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));String lineRead;while((lineRead = httpResponseReader.readLine()) != null) {    System.out.println(lineRead);}

  

转载于:https://www.cnblogs.com/hephec/p/4570577.html

你可能感兴趣的文章
字节流与字符流
查看>>
.net常见的一些面试题
查看>>
OGRE 源码编译方法
查看>>
上周热点回顾(10.20-10.26)
查看>>
C#正则表达式引发的CPU跑高问题以及解决方法
查看>>
云计算之路-阿里云上:“黑色30秒”走了,“黑色1秒”来了,真相也许大白了...
查看>>
APScheduler调度器
查看>>
设计模式——原型模式
查看>>
【jQuery UI 1.8 The User Interface Library for jQuery】.学习笔记.1.CSS框架和其他功能
查看>>
如何一个pdf文件拆分为若干个pdf文件
查看>>
web.xml中listener、 filter、servlet 加载顺序及其详解
查看>>
前端chrome浏览器调试总结
查看>>
获取手机验证码修改
查看>>
数据库连接
查看>>
python中数据的变量和字符串的常用使用方法
查看>>
等价类划分进阶篇
查看>>
delphi.指针.PChar
查看>>
Objective - C基础: 第四天 - 10.SEL类型的基本认识
查看>>
java 字符串转json,json转对象等等...
查看>>
网站访问者UA检测及跳转
查看>>