java - 无法使用 HttpURLConnection 上传文件

标签 java httpurlconnection

我一直在使用 HttpURLConnection 上传文件,但在执行时出现如下错误:

request was rejected because no multipart boundary was found

以下是我的代码片段

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();
    }
}

关于java - 无法使用 HttpURLConnection 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833520/

相关文章:

java - Java 中双链表的冒泡排序

java - 初始项目错误 libgdx 1.0

android - Android HttpURLConnection.setChunkedStreamingMode() 的默认 block 长度?

java - httpUrlconnection 向任何调用返回 500 错误代码

java - 超时没有限制吗? - HttpsURL连接

android - HttpURLConnection 后 : Output stream has no effect?

java - 有没有办法在 imageView 上实现重做和撤消

java - 使用 corejava 程序进行无密码的 MySQL 连接(用户 'root' @'localhost' 的访问被拒绝)

Java:如何使用大量谓词过滤大量对象?

java - 通过 Http 调用在 Elastic Search 中索引文档时,PUT/POST 数据的大小是否有限制?