有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

apache使用Java以表单数据形式上载文件

我正在尝试使用ApacheAPI在Java中执行HTTP Post请求

对于curl,请求如下所示

curl https://host/upload
-X POST
-H "Authorization: Bearer xxx"
-H "Content-Type: multipart/form-data"
-H "Accept: application/json"
-F "file=@{PathToImage}" -F "type=file" 

当使用CURL运行它时,这种方法可以很好地工作,但当使用以下Java代码运行它时,服务器返回500er结果

    final HttpPost httppost = new HttpPost("https://host/upload");
    httppost.addHeader("Authorization", "Bearer xxx");
    httppost.addHeader("Accept", "application/json");
    httppost.addHeader("Content-Type", "multipart/form-data");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    final File file = new File("c:\\tmp\\myfile.pdf");
    builder.addBinaryBody("file", file);
    builder.addTextBody("type", "file");
    final HttpEntity entity = builder.build();
    httppost.setEntity(entity);
    final HttpResponse response = httpclient.execute(httppost);
    httpclient.close();

你知道我在这里遗漏了什么吗


共 (3) 个答案

  1. # 1 楼答案

    问题类似。但我相信答案是将addBinary更改为addPart

    final HttpPost httppost = new HttpPost("https://host/upload");
    httppost.addHeader("Authorization", "Bearer xxx");
    httppost.addHeader("Accept", "application/json");
    httppost.addHeader("Content-Type", "multipart/form-data");
    
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    final File file = new File("c:\\tmp\\myfile.pdf");
    builder.addPart("file", new FileBody(file));
    builder.addTextBody("type", "file");
    final HttpEntity entity = builder.build();
    httppost.setEntity(entity);
    final HttpResponse response = httpclient.execute(httppost);
    httpclient.close();
    
  2. # 2 楼答案

    尝试baeldung multipart upload article建议的语法:

    String textFileName = "c:\\tmp\\myfile.pdf";
    final File file = new File(textFileName);
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, textFileName);
    builder.addTextBody("type", "file", ContentType.DEFAULT_BINARY);
    

    create a multipart entity is to use the addBinaryBody and AddTextBody methods. These methods work for uploading text, files, character arrays, and InputStream objects.

  3. # 3 楼答案

    试试这样吧

            //import javax.net.ssl.HttpsURLConnection;
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            String encoding = Base64.getEncoder().encodeToString((user + ":" + psw).getBytes("UTF-8"));
    
            con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Java client");
    
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(val);