Getting a file from an http request in java
Solution 1
public byte[] download(URL url) throws IOException {
URLConnection uc = url.openConnection();
int len = uc.getContentLength();
InputStream is = new BufferedInputStream(uc.getInputStream());
try {
byte[] data = new byte[len];
int offset = 0;
while (offset < len) {
int read = is.read(data, offset, data.length - offset);
if (read < 0) {
break;
}
offset += read;
}
if (offset < len) {
throw new IOException(
String.format("Read %d bytes; expected %d", offset, len));
}
return data;
} finally {
is.close();
}
}
Edit: Cleaned up the code.
Solution 2
Check out the URL and URLConnection classes. Here's some documentation: http://www.exampledepot.com/egs/java.net/Post.html
Solution 3
If the intention is to run another resource while your servlet is executing with out transferring control to the other resource you can try using include(request, response).
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/url of other resource");
if (dispatcher != null)
dispatcher.include(request, response);
}
You may put this on a servlet and the result of the other resource is included on your servlet.
EDIT: Since you are looking to get a file back then this solution works for that too.
![Fantastic Mr Fox](https://i.stack.imgur.com/Inny3.jpg?s=256&g=1)
Fantastic Mr Fox
Updated on October 27, 2020Comments
-
Fantastic Mr Fox over 3 years
I am wondering if there are any compiler flags you can set to pick up this case. Say I have the following files:
a.h
class a { public: int lala(void); int lala2(void); };
a.cpp
#include "a.h" int a::lala(void) { return 5; }
main.cpp
#include <iostream> #include "a.h" int main() { a thi; std::cout << thi.lala() << std::endl; return 0; }
The problem here is that the function lala2 is not implemented and although its not used not even a warning is issued.
So i don't know how it led to this but basically in a large portion of code there was an un-implemented function. I am just wondering if there are any compiler flags that will allow us to pick this up? Using
g++ -pedantic -Wall
was not enough.-
rhughes about 10 yearsIf you tried to use this method you would probably get a linker error.
-
Fantastic Mr Fox about 10 years@rhughes, Correct but I would like to get a compiler warning so that I can pick up this function.
-
Klaus about 10 yearsThe compiler can't see that the function is not needed and not defined. This can only be done in link stage.
-
-
RodeoClown over 15 yearsThanks Vincent. It doesn't look like that will quite meet what I am looking for - I'm not looking to include anything in the response. There is no response in this instance (it is a scheduled task that runs purely server-side).