Apache httpclient是否支持multipart \ related?

时间:2014-01-25 04:02:05

标签: apache-httpclient-4.x

默认情况下,Apache Http客户端MIME API版本4.3.2将内容类型作为multipart / form-data发送。有没有其他方法可以将内容类型更改为与多部分相关的内容?

3 个答案:

答案 0 :(得分:0)

一个简单的解决方案是自己设置标题的值:

HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.CONTENT_TYPE, "multipart/related");

希望这会有所帮助。

答案 1 :(得分:0)

这是一个适合我的实现: 我已将类型设置为application / octet-stream,因为我不知道您正在上传哪种数据..可以随意更改此内容。

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class UploadMimeMultipartRelated  {

    /** Logger. */
    private static final Logger LOG = LoggerFactory.getLogger(UploadMimeMultipartRelated.class);

    /** Mime type */
    private static final String CONTENT_TYPE_MULTIPART = "multipart/related";
    private static final String CONTENT_TYPE = "application/octet-stream";
    private static final String BOUNDARY = "--upload_boundary--";

    private static final String URL = "http://.....";

    @Override
    public void uploadFiles(List<String> filePathlist) {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setBoundary(BOUNDARY);
        for (String filepath : filePathlist) {
            multipartEntityBuilder.addBinaryBody("file_upload", new File(filepath), ContentType.create(CONTENT_TYPE), "filename");
        }
        HttpEntity entity = multipartEntityBuilder.build();


        HttpPost httpPost = new HttpPost(URL);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_MULTIPART+";type="+CONTENT_TYPE+";boundary="+BOUNDARY);
        httpPost.setEntity(entity);


        CloseableHttpResponse response;
        try {
            response = httpClient.execute(httpPost);
            response.getEntity();
            response.close();
            httpClient.close();
        } catch (ClientProtocolException e) {
            LOG.error("ClientProtocolException during upload",e);
        } catch (IOException e) {
            LOG.error("IOException during upload",e);
        }

    }

答案 2 :(得分:0)

这是使用任何子类型

的多部分实体构建请求的推荐方法
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && TextUtils.isEmpty(price_val) && mImageUri!=null)