使用Apache MultipartEntityBuilder上传Http文件

时间:2015-08-08 12:00:42

标签: java c# http apache-httpclient-4.x

下面是c#中文件上传的Http post方法。在使用apache库的java中此代码的等价物是什么。如何在java中添加contentDisposition并在其中传递byte数组值。提供一些在线参考非常感谢。

C#代码

            byte[] date = //file in byte format
            var fileContent = new StreamContent(new MemoryStream(data));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "\"files\"",
                FileName = "\"" + filename + "\""
            }; // the extra quotes are key here
            fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            var content = new MultipartFormDataContent();
            content.Add(fileContent);

            HttpResponseMessage response = null;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _url + uri);
            request.Content = content;

我的Java代码

         StringBody name = new StringBody("\"files\"", ContentType.MULTIPART_FORM_DATA);
         StringBody file = new StringBody("\"" + filename + "\"", ContentType.MULTIPART_FORM_DATA);

         HttpEntity entity = MultipartEntityBuilder.create()
                    .addPart("Name", name)
                    .addPart("FileName", file)
                    .addBinaryBody("file", data)
                    .build();

        Postmethod = new HttpPost(_url + uri);
        Postmethod.addHeader(useragent);
        Postmethod.addHeader(Accesstoken);
        Postmethod.setEntity(entity);
        Postmethod.addHeader("content-type", contentType);
        response = httpClient.execute(Postmethod);

响应状态代码为400.我哪里出错了?

先谢谢..

0 个答案:

没有答案