【问题标题】:Send file using POST from a Java使用 POST 从 Java 发送文件
【发布时间】:2019-02-27 16:33:15
【问题描述】:

我正在尝试使用 java 发送文件,我有一个正在运行的现有 python,需要转换为 java。

下面是我的python代码,

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

我的java代码

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

现在我不确定如何将文件传递给发布请求

【问题讨论】:

标签: java python httpurlconnection


【解决方案1】:
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");
            }
        });
    }
}

试试这个

【讨论】:

猜你喜欢
  • 2015-09-22
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2015-03-19
  • 1970-01-01
相关资源
最近更新 更多