如何在JAVA中通过POST上传文件

时间:2013-06-25 08:02:23

标签: java rest post file-upload httpurlconnection

我正在尝试使用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代码创建上传,我将接下来是原始的:

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 ......

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

0 个答案:

没有答案