问题描述
我正在尝试使用
上传文件这适用于大多数文件,但对于某些文件似乎失败了:文件已上传(我可以在服务器上看到它并且它与源文件的大小相同)。但是,一旦文件上传,client.execute(post)
调用就永远不会返回。失败的文件似乎是较大的文件(> 800M)。
代码如下所示。
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.io.IoUtils;
import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.multipartentityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HttpFileUpload2 {
public static void main(String args[]) throws Exception {
log.info("Starting...");
String url = "https://url-of-the-rest-api/api/2.0/dbfs/put";
String token = "security-token";
String path = "/path/on/the/server/for/myfile.txt";
String srcFile = "C:\\path\\to\\myfile.txt";
File file = new File(srcFile);
HttpPost post = new HttpPost(url);
//
multipartentityBuilder builder = multipartentityBuilder.create();
builder.setMode(HttpMultipartMode.broWSER_COMPATIBLE);
builder.addTextBody("path",path,ContentType.TEXT_PLAIN);
log.info("Converting to byte[]...");
byte[] bytes = IoUtils.toByteArray(new FileInputStream(file));
log.info("Adding to builder");
builder.addBinaryBody("upload-file",bytes,ContentType.APPLICATION_OCTET_STREAM,file.getName());
httpentity entity = builder.build();
//
post.setEntity(entity);
post.addHeader("Authorization","Bearer " + token);
CloseableHttpClient client = HttpClients.createDefault();
log.info("Doing post...");
HttpResponse httpResponse = client.execute(post);
String response = HttpRequestClient.getResponse(httpResponse.getEntity().getContent());
// we never get to this line
log.info("Got response: \n" + response);
log.info("Done.");
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)