无法使用HttpURLConnection上传文件

问题描述 投票:1回答:2

我一直在使用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();

我该如何纠正这个问题?

java httpurlconnection
2个回答
1
投票

您需要Multipart File上传: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();
    }
}

0
投票

您将文件复制到输出流的代码是错误的,删除该行

PrintWriter pw = new PrintWriter(os);

而不是使用pw,用正确的读取字节数写入os,

os.write(buffer, 0 bytes_read);
© www.soinside.com 2019 - 2024. All rights reserved.