Java中带有文件卷曲模拟的http发送数据库
我想使用与以下示例相当的Java发送POST请求:
echo "param value" | curl --data-binary @- -uuser:pass https://url
我尝试了ApacheHTTPSetEntity(FileEntity),400个错误请求
我尝试了ApacheHTTPSetEntity(MultiPartEntity),400个错误请求
// ----------------
// General part
String url = "https://url";
String content = "param" + " " + "value";
File file = new File("test.txt");
try {
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
String encoding = Base64.getEncoder().encodeToString(("user:pass").getBytes());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);
// -----------------
// 1. FileEntity try
FileEntity reqEntity = new FileEntity (file, ContentType.DEFAULT_BINARY);
post.setEntity(reqEntity);
HttpResponse response = httpclient.execute(post);
// ----------------
// 2. Multipart try
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, org.apache.http.entity.ContentType.DEFAULT_BINARY);
mpEntity.addPart("userfile", cbFile);
post.setEntity(mpEntity);
HttpResponse response = httpclient.execute(post);
我本来希望得到200,但收到了400个错误的请求
最初的CURL工作正常
# 1 楼答案
边界参数问题不在
Content-Type
头中实际上,如果您使用的是
multipart/
内容类型之一,那么实际上需要在Content-Type
头中指定边界参数,但是在这里,如果curl请求不尝试生成任何边界值,没有边界值,服务器(在HTTP request
的情况下)将无法解析有效负载