我想使用以下 CURL 示例的 Java 等效物发送 POST 请求:
echo "param value" | curl --data-binary @- -uuser:pass https://url
我试过 apache http setEntity(FileEntity entity(,400 错误请求
我试过 apache http setEntity(MultiPartEntity entity(,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
的情况下(将无法解析有效负载