📜 ⬆️ ⬇️

POST of java

Today I will share this experience. Having heard the fashionable word REST , we decided to immediately apply this trend in the project. The project needed to store pictures for the relevant resources. And the following agreement was chosen:

The model, by the way, paid off. We use to this day. But in the process of developing the question arose how to try and test this miracle. Moreover, the implementation of this functionality on the client (Flex, btw) was not yet ready.



A similar solution was found on the Internet: http://www.devx.com/Java/Article/17679/1954
')
A simple “library” of one class, with no additional dependencies, sends a file with a POST request in one method, as the browser or Flex client does in our case.

InputStream serverInput = ClientHttpRequest.post(
new java.net.URL(urlString),
new Object[]{
"name", "J.Doe",
"email", "abuse@spamcop.com",
"test.txt", new
File("c:\w\image.jpg")
});


The servlet accepts:

-----------------------------k8rws1oxpkuv1g53x0ud6a004-j12py3q5jcay
Content-Disposition: form-data; name="name"

J.Doe
-----------------------------k8rws1oxpkuv1g53x0ud6a004-j12py3q5jcay
Content-Disposition: form-data; name="email"

abuse@spamcop.com
-----------------------------k8rws1oxpkuv1g53x0ud6a004-j12py3q5jcay
Content-Disposition: form-data; name="test.txt"; filename="image.jpg"
Content-Type: image/jpeg

...


For completeness, I’ll say that on the server side, the apache commons fileupload library is used:

ServletFileUpload upload = new ServletFileUpload();

FileItemIterator iter = upload.getItemIterator(httpServletRequest);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (!item.isFormField()) {
InputStream stream = item.openStream();

//
}
}


* This source code was highlighted with Source Code Highlighter .

Source: https://habr.com/ru/post/50406/


All Articles