我想使用与以下CURL示例等效的Java发送POST请求:
echo "param value" | curl --data-binary @- -uuser:pass https://url
我尝试过Apache http setEntity(FileEntityentity),400错误的请求
我尝试过apache http setEntity(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可以正常工作
边界参数问题不在Content-Type
标头中
实际上,如果您使用的是multipart/
内容类型之一,则实际上需要在Content-Type
标头中指定边界参数,但是在此处使用curl请求时,请不要尝试生成任何边界值,而没有边界值的服务器(在HTTP request
的情况下)将无法解析有效载荷