【问题标题】:How to add header to multi part request?如何将标头添加到多部分请求?
【发布时间】:2017-04-10 12:37:38
【问题描述】:

我有一个包含 3 个部分的多部分请求,每个部分都包含自己的正文和标头,所以我想要在其中一个部分上添加一个自定义标头。我试图用改造和 okhttp 来构建请求,但他们没有提供这样做的选项。有什么想法吗?

编辑:这是基于question

【问题讨论】:

    标签: android post http-headers http-post retrofit2


    【解决方案1】:

    试试下面的代码:

    public HttpResponse multiPartRequest(String url, String token, File file) {
    
    client = new DefaultHttpClient();
    
    HttpPost request = new HttpPost(url);
    
    HttpResponse response = null;
    
    DRPContentForUpload content = new DRPContentForUpload(file);
    String jsonObject = DRPJSONConverter.toJson(content);
    String BOUNDARY= "--eriksboundry--";
    
    request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
    request.addHeader("X-AUTHORIZATION",token);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY,Charset.defaultCharset());
    try {
    
    
        entity.addPart("file01", new StringBody(jsonObject));
    
        entity.addPart("file01", new FileBody(file));
    
        request.addHeader("Accept-Encoding", "gzip, deflate");
    
    } catch (UnsupportedEncodingException e) {
        Log.v("encoding exception","E::: "+e);
        e.printStackTrace();
    }
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
    request.setEntity(entity);
    
    try {
    
    
    
    
        response = client.execute(request);
    
    
    
    } catch (ClientProtocolException e) {
    
        e.printStackTrace();
    } catch (IOException e) {
    
        e.printStackTrace();
    }
    
    
    return response;
    

    }

    【讨论】:

    • 从外观上看,这是一个标准请求,其中一个部分没有自定义标头,例如,可能是文件的第 1 部分将具有标准标头和额外的标头。这样更有意义吗?
    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2012-12-22
    • 1970-01-01
    • 2012-12-01
    • 2017-02-15
    相关资源
    最近更新 更多