簡體   English   中英

無法使用 HttpURLConnection 上傳文件

[英]Unable to upload file using HttpURLConnection

我一直在使用 HttpURLConnection 上傳文件,但在執行時出現如下錯誤:

請求被拒絕,因為沒有找到多部分邊界

以下是我的代碼片段

File importFile = new File(args[0]);
url = new URL("http://localhost:8888/ajax/import?action=csv&session=" + sessionId + "&folder=36");
URLConnection uc = url.openConnection();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Cookie", cookieStringBuffer.toString());
connection.setRequestProperty("content-type", "multipart/form-data");
connection.setDoOutput(true);
connection.connect();

FileInputStream is = new FileInputStream(importFile);
OutputStream os = connection.getOutputStream();
PrintWriter pw = new PrintWriter(os);
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = is.read(buffer)) != -1) {
   //os.write(buffer, 0, bytes_read);
   pw.print(buffer); // here we "send" our body!
}
pw.flush();
pw.close();

我該如何糾正這個問題?

您需要分段文件上傳: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload

提供的鏈接中的示例:

package com.commonsbook.chap9;
import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {
    private static String url =
      "http://localhost:8080/HttpServerSideApp/ProcessFileUpload.jsp";

    public static void main(String[] args) throws IOException {
        HttpClient client = new HttpClient();
        MultipartPostMethod mPost = new MultipartPostMethod(url);
        client.setConnectionTimeout(8000);

        // Send any XML file as the body of the POST request
        File f1 = new File("students.xml");
        File f2 = new File("academy.xml");
        File f3 = new File("academyRules.xml");

        System.out.println("File1 Length = " + f1.length());
        System.out.println("File2 Length = " + f2.length());
        System.out.println("File3 Length = " + f3.length());

        mPost.addParameter(f1.getName(), f1);
        mPost.addParameter(f2.getName(), f2);
        mPost.addParameter(f3.getName(), f3);

        int statusCode1 = client.executeMethod(mPost);

        System.out.println("statusLine>>>" + mPost.getStatusLine());
        mPost.releaseConnection();
    }
}

您將文件復制到 output stream 的代碼是錯誤的,刪除該行

PrintWriter pw = new PrintWriter(os);

而不是使用 pw,而是使用讀取的正確字節數寫入 os,

os.write(buffer, 0 bytes_read);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM