gpt4 book ai didi

java - 从 Java 使用 POST 发送文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:06 25 4
gpt4 key购买 nike

我正在尝试使用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");

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

最佳答案

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");
}
});
}
}

试试这个

关于java - 从 Java 使用 POST 发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54910189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com