3

我正在尝试通过在 JAVA 中使用 POST 来上传文本文件。但是我发送的数据包缺少文件内容的正文。

如果我使用 POSTMAN chrome ext,我会收到数据包:

POST http://localhost:8080/storm-webapp/load-scripts/ HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 205
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryq3Ss6jb9i23grqZA
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: CoreI18n=en-US

------WebKitFormBoundaryq3Ss6jb9i23grqZA
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: text/plain

This is a test text to upload
------WebKitFormBoundaryq3Ss6jb9i23grqZA--

如果我正在通过 java 代码创建上传,我将得到下一个 raw :

POST http://localhost:8888/storm-webapp/load-scripts/ HTTP/1.1
Content-Type: multipart/form-data; boundary=----13f7a4f68b9
User-Agent: Java/1.7.0_17
Host: localhost:8888
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 0

如您所见,我缺少身体的整个部分......我使用的代码是:

    BufferedReader reader = null;
    File file = new File("HelloWorld.txt");

    String boundary = "WebKitFormBoundary" + Long.toHexString(System.currentTimeMillis());
    HttpURLConnection conn = (HttpURLConnection) new URL(rest).openConnection();
    /*************Header*****************/
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----" + boundary);
    /*********Body**************/
    PrintWriter writer = null;
    writer = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
    writer.println("------" + boundary);
    writer.println("Content-Disposition: form-data; name=\"file\"; filename=\"HelloWorld.txt\"");
    writer.println("Content-Type: text/plain");
    writer.println();

    reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    for (String line; (line = reader.readLine()) != null;) {
        writer.println(line);
    }
    writer.println("------" + boundary + "--");
    /*******************************************************/

    reader.close();

    int responseCode = conn.getResponseCode();

    System.out.println("ResponseCode is : " + responseCode);

并且响应代码是 400 ...

任何想法,我做错了什么?谢谢

4

0 回答 0