我正在尝试使用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");
现在我不确定如何将文件传递到邮寄请求
答案 0 :(得分: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");
}
});
}
}
尝试一下