1

I am trying to send file using java, i have a existing python which is working which needs to be converted to java.

Below is my python code,

with io.open('test.text', 'rb') as f:
r = requests.request("POST",'http://my_url/post', data=f)

My java code

HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://my_url/post");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");

Now i am not sure how to pass the file to the post request

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
Cedric
  • 107
  • 15
  • Check answer to this question https://stackoverflow.com/questions/6917105/java-http-client-to-upload-file-over-post. – vmaroli Feb 27 '19 at 16:39

1 Answers1

0
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

public class PostFile {
    public static void main(String[] aaa) throws URISyntaxException{
        final URI uri = new URIBuilder("http://httpbin.org/post")
                .build();
        HttpPost request = new HttpPost(uri);

        File f = new File("file.txt");
        request.setEntity(new FileEntity(f));

        CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
        client.start();
        client.execute(request, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(HttpResponse httpResponse) {
                System.out.println("completed: " + httpResponse);
            }

            @Override
            public void failed(Exception e) {
                System.out.println("failed");
            }

            @Override
            public void cancelled() {
                System.out.println("cancelled");
            }
        });
    }
}

Try this

Michel_T.
  • 2,741
  • 5
  • 21
  • 31
  • Here is a link for multi-part files - https://blog.morizyun.com/blog/android-httpurlconnection-post-multipart/index.html – Spindoctor Feb 27 '19 at 17:07