Java Multipart POST从WebApi服务器返回MediaTypeNotSupported

本文关键字:服务器 返回 MediaTypeNotSupported WebApi Multipart POST Java | 更新日期: 2023-09-27 18:24:24

我正在使用"MultipartUtil"类,如SO问题的第一个答案中所述。

我通过添加额外的行更改了构造函数,如下所示:

public MultiPartUtil(String requestURL, String charset) throws IOException {
    this.charset = charset;
    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";
    URL url = new URL(requestURL);
    httpConn = (HttpsURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestMethod("POST");
    httpConn.setRequestProperty("Connection", "Keep-Alive");
    httpConn.setRequestProperty("Cache-Control", "no-cache");
    httpConn.setRequestProperty("enctype", "multipart/form-data");
    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "MTApp");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}

上传文件的代码是:

MultiPartUtil multipart = new MultiPartUtil(url, "UTF-8");
multipart.addFilePart("archive", new File("archivefile.zip"));
multipart.finish();

在服务器端,我有:

[HttpPost]
public void upload()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, "This request is not properly formatted"));
    }
    //Process file here...
}

在不允许接受文件的Java代码中,我可能缺少什么?

Java Multipart POST从WebApi服务器返回MediaTypeNotSupported

你能试着把边界改成---1234567---而不是===1234567===吗?

因为http标头参数中不允许使用令牌。