Java http save file

Upload files from Java client to a HTTP server

I’d like to upload a few files to a HTTP server. Basically what I need is some sort of a POST request to the server with a few parameters and the files. I’ve seen examples of just uploading files, but didn’t find how to also pass additional parameters. What’s the simplest and free solution of doing this? Does anyone have any file upload examples that I could study? I’ve been googling for a few hours, but (maybe it’s just one of those days) couldn’t find exactly what I needed. The best solution would be something that doesn’t involve any third party classes or libraries.

8 Answers 8

You’d normally use java.net.URLConnection to fire HTTP requests. You’d also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

String url = "http://example.com/upload"; String charset = "UTF-8"; String param = "value"; File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); ) < // Send normal param. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Send text file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); >// Request is lazily fired whenever you need to obtain information about response. int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode); // Should be 200 

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can’t use and don’t need it at the client side.

See also

Источник

How to download a file via HTTP GET and HTTP POST in Java without using any external libraries

Apart from uploading a file to a HTTP server endpoint, another common task for a Java HTTP client is to download a file from a HTTP server. Even though there are many Java external libraries to help us do so, using the facilities in the Java standard runtime installation is not difficult. Furthermore, we will be able to keep our Java application leaner if we can download files without additional dependencies.

In case you need a reference, this is how to download a file via HTTP GET and HTTP POST in Java without using any external libraries.

Downloading a file from a HTTP server endpoint via HTTP GET

Generally, downloading a file from a HTTP server endpoint via HTTP GET consists of the following steps:

  • Construct the HTTP GET request to send to the HTTP server.
  • Send the HTTP request and receive the HTTP Response from the HTTP server.
  • Save the contents of the file from HTTP Response to a local file.
Читайте также:  Красивое всплывающее окно html

Java codes to download a file from a HTTP server endpoint via HTTP GET

Given these points, let us modify the codes from how to send a HTTP GET request in Java to save the contents of the file from a HTTP Response to a local file:

import java.io.IOException; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; public class HttpGetDownloadFileExample < public static void main(String[] args) < ReadableByteChannel readableChannelForHttpResponseBody = null; FileChannel fileChannelForDownloadedFile = null; try < // Define server endpoint URL robotsUrl = new URL("http://www.techcoil.com/robots.txt"); HttpURLConnection urlConnection = (HttpURLConnection) robotsUrl.openConnection(); // Get a readable channel from url connection readableChannelForHttpResponseBody = Channels.newChannel(urlConnection.getInputStream()); // Create the file channel to save file FileOutputStream fosForDownloadedFile = new FileOutputStream("robots.txt"); fileChannelForDownloadedFile = fosForDownloadedFile.getChannel(); // Save the body of the HTTP response to local file fileChannelForDownloadedFile.transferFrom(readableChannelForHttpResponseBody, 0, Long.MAX_VALUE); >catch (IOException ioException) < System.out.println("IOException occurred while contacting server."); >finally < if (readableChannelForHttpResponseBody != null) < try < readableChannelForHttpResponseBody.close(); >catch (IOException ioe) < System.out.println("Error while closing response body channel"); >> if (fileChannelForDownloadedFile != null) < try < fileChannelForDownloadedFile.close(); >catch (IOException ioe) < System.out.println("Error while closing file channel for downloaded file"); >> > > >

As shown above, we had created a class with a main method. When the main method is executed, our Java program does several things.

Firstly, we had declared an instance of ReadableByteChannel and an instance of FileChannel to contain null values so as to facilitate closure in the finally block.

After we had done so, we define a try block for running the file download logic that may throw checked exceptions.

Within the try block, we first use an instance of URL to get an instance of HttpURLConnection that points to a HTTP server endpoint for the file that we wish to download.

Once we have done so, we get an instance of ReadableByteChannel that is mapped to the input stream of urlConnection . In addition, we set it to the readableChannelForHttpResponseBody variable for manipulation later.

After we had an instance of ReadableByteChannel , we then proceed to get a FileChannel that will point to a local file path where we want to save the downloaded file. In this case, we want to save the downloaded file as robots.txt in the same directory where we run our Java program.

Finally, we use fileChannelForDownloadedFile.transferFrom method on readableChannelForHttpResponseBody to save the contents of the HTTP response body to the local file.

Downloading a file from a HTTP server endpoint via HTTP POST

There can be cases where the client need to supply some information to the HTTP server in order to download a file. In such a situation, HTTP POST is a more appropriate HTTP method to use for downloading the file.

As with HTTP GET, downloading of a file from the HTTP server via HTTP POST consists of the following steps:

  • Construct the HTTP POST request to send to the HTTP server.
  • Send the HTTP request and receive the HTTP Response from the HTTP server.
  • Save the contents of the file from HTTP Response to a local file.

Java codes to download a file from a HTTP server endpoint via HTTP POST

Given these points, let’s modify the Java code from how to send a HTTP POST request in Java to save the contents of the file from a HTTP Response to a local file:

import java.io.BufferedWriter; import java.io.IOException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; public class HTTPPostDownloadFileExample < public static void main(String[] args) throws IOException < // Define the server endpoint to send the HTTP request to URL serverUrl = new URL("https://www.techcoil.com/process/proof-of-concepts/userNameAndLuckyNumberTextFileGeneration"); HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection(); // Indicate that we want to write to the HTTP request body urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); // Writing the post data to the HTTP request body BufferedWriter httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream())); httpRequestBodyWriter.write("visitorName=Johnny+Jacobs&luckyNumber=1234"); httpRequestBodyWriter.close(); // Get a readable channel from url connection ReadableByteChannel readableChannelForHttpResponseBody = Channels.newChannel(urlConnection.getInputStream()); // Create the file channel to save file FileOutputStream fosForDownloadedFile = new FileOutputStream("luckyNumber.txt"); FileChannel fileChannelForDownloadedFile = fosForDownloadedFile.getChannel(); // Save the contents of HTTP response to local file fileChannelForDownloadedFile.transferFrom(readableChannelForHttpResponseBody, 0, Long.MAX_VALUE); >>

As shown above, we had created a class with a main method which will propagate any occurrences of IOException back to the caller. When the main method is executed, our Java program does several things.

Читайте также:  Java ssl socket connect

First, it creates an instance of HttpURLConnection , urlConnection , that maps to the HTTP server endpoint at https://www.techcoil.com/process/proof-of-concepts/userNameAndLuckyNumberTextFileGeneration . Given that, we then configure urlConnection to allow us to write to the HTTP request body via urlConnection.setDoOutput(true). After that, we set the HTTP method of the HTTP request as POST via urlConnection.setRequestMethod(«POST») .

Next, we use an instance of BufferedWriter to write some POST variables to the HTTP request body.

Once we had written the POST variables, we then get an instance of ReadableByteChannel from the input stream of urlConnection . Given that instance, we will then be able to read from the body of the HTTP response.

After we had an instance of ReadableByteChannel , we then proceed to get an instance of FileChannel that will point to a local file path where we want to save the downloaded file. In this case, we will save the downloaded file as luckyNumber.txt in the same directory where we run our Java program.

Finally, we use fileChannelForDownloadedFile.transferFrom on readableChannelForHttpResponseBody to save the contents of the HTTP response body to the local file.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.

Источник

How to download an HttpResponse into a file?

My android app uses an API which sends a multipart HTTP request. I am successfully getting the response like so:

post.setEntity(multipartEntity.build()); HttpResponse response = client.execute(post); 

The response is the contents of an ebook file (usually an epub or mobi). I want to write this to a file with a specified path, lets says «/sdcard/test.epub». File could be up to 20MB, so it’ll need to use some sort of stream, but I can just can’t wrap my head around it. Thanks!

3 Answers 3

well it is a simple task, you need the WRITE_EXTERNAL_STORAGE use permission.. then simply retrieve the InputStream

InputStream is = response.getEntity().getContent(); 

Create a FileOutputStream

FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "test.epub")) 

and read from is and write with fos

int read = 0; byte[] buffer = new byte[32768]; while( (read = is.read(buffer)) > 0) < fos.write(buffer, 0, read); >fos.close(); is.close(); 

Perfect. The fact that response.getEntity().getContent() gives an input stream was the missing piece of the puzzle. Thanks.

public HttpResponse setHTTPConnection() throws IOException, NullPointerException, URISyntaxException
File downloadedFile = new File("filePathToSave"); HttpResponse fileToDownload = setHTTPConnection(); try < FileUtils.copyInputStreamToFile(fileToDownload.getEntity().getContent(), downloadedFile); >finally

Источник

Java download file

Often it is required to download a file directly from a URL and save to a directory on local system such as downloading a file from a remote repository. This requires reading a file from url and writing it to a local file.
This article will share different methods to download a file from URL in java. Methods defined here are applicable to all types of file such as a pdf file, an exe file, a txt file or a zip file etc.

  1. Create a connection to the given file url.
  2. Get input stream from the connection. This stream can be used to read file contents.
  3. Create an output stream to the file to be downloaded.
  4. Read the contents from the input stream and write to the output stream.
Читайте также:  Php время работы скрипта php ini

Java code to download file from URL with this method is given below.

import java.net.URL; import java.net.URLConnection; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileDownloader < public static void main(String[] args) < OutputStream os = null; InputStream is = null; String fileUrl = "http://200.34.21.23:8080/app/file.txt"; String outputPath = "E:\\downloads\\downloaded.txt"; try < // create a url object URL url = new URL(fileUrl); // connection to the file URLConnection connection = url.openConnection(); // get input stream to the file is = connection.getInputStream(); // get output stream to download file os = new FileOutputStream(outputPath); final byte[] b = new byte[2048]; int length; // read from input stream and write to output stream while ((length = is.read(b)) != -1) < os.write(b, 0, length); >> catch (IOException e) < e.printStackTrace(); >finally < // close streams if (os != null) os.close(); if (is != null) is.close(); >> >

Remember that the output and input paths should end with the file name else there will be an error.

All the methods in this post read a file at a remote URL. If you want to read a file at local system, then refer this post.

  1. Create an input stream to the file to be downloaded.
  2. Create a new channel that will read data from this input stream.
  3. Create an output stream that will write file contents after reading it from the channel created in Step 2.
  4. Get the channel from this output stream and write the contents from channel created in Step 2.

You will understand the algorithm better after looking at the below code example.

import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.io.File; public class FileDownloader < public static void main(String[] args) < try < String fileUrl = "http://200.34.21.23:8080/app/file.pdf"; String outputPath = "E:\\downloads\\downloaded.pdf"; URL url = new URL(fileUrl); // create an input stream to the file InputStream inputStream = url.openStream(); // create a channel with this input stream ReadableByteChannel channel = Channels.newChannel( url.openStream()); // create an output stream FileOutputStream fos = new FileOutputStream( new File(outputPath)); // get output channel, read from input channel and write to it fos.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); // close resources fos.close(); channel.close(); >catch(IOException e) < e.printStackTrace(); >> >

Note that transferFrom() method of a channel takes 3 arguments.
1. input file channel,
2. position at which it will start reading the file, 0 here means the beginning of file, and
3. number of bytes that will be transferred at one time. This value is set to a very large value( Long.MAX_VALUE ) for higher efficiency.

Learn different methods of writing to a file here .

Method 3 : Using Apache Commons IO Library
Apache Commons IO Library has a org.apache.commons.io.FileUtils class which contains a method copyURLToFile() .

This method takes two arguments:
1. java.net.URL object pointing to the source file, and
2. java.io.File object which points to an output file path.

Remember that both paths should contain the name of file at the end and output path should be a location on local system at which the file will be downloaded.
copyURLToFile() reads the file from remote location and copies it to the local machine. Example,

import org.apache.commons.io.FileUtils; public class FileDownloader < public static void main(String[] args) < String fileUrl = "http://200.34.21.23:8080/app/file.zip"; String outputPath = "E:\\downloads\\downloaded.zip"; FileUtils.copyURLToFile(new URL(fileUrl), new File(outputPath)); >>

You can add Apache Commons IO dependency to your project as per the build tool.

// Gradle
compile group: ‘org.apache.commons’, name: ‘commons-io’, version: ‘1.3.2’

Hope the article was useful in explaining different ways to download a file from URL in java.
Do not forget to click the clap below.

Источник

Оцените статью