【问题标题】:HttpPost write body as well as the request parametersHttpPost 写入正文以及请求参数
【发布时间】:2015-07-01 14:03:22
【问题描述】:

我正在使用 Apache 的 HttpPost。我正在尝试将文件上传到网络服务器,结果如下:

POST 站点/上传?uploadType=chunked&requestId={requestId} HTTP/1.1

主持人:

接受:应用程序/xml

授权令牌:

请求参数

requestId 当前上传会话的唯一标识符。

请求标头

Host Web 服务器的主机名。

接受 响应的格式。有效值为:application/xml 或 application/json。

Authtoken 登录成功后收到的认证令牌。

FileEOF 指定当前文件块是否已到达文件末尾。允许的值为 0 和 1。文件结尾表示值 1。

请求正文

以字节为单位包含文件块的内容。

我想出的是这样的:

HttpPost post = new HttpPost(url);
            post.setHeader("Authtoken", params.get("token"));
            String fileName = file.getName();
            long offset = Long.parseLong(chunkOffset);
            //...
            post.setHeader("FileEOF", eof);
            /*List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("requestId", requestId));
            post.setEntity(new UrlEncodedFormEntity(postParameters));*/

            fileInputStream.skip(offset);
            fileInputStream.read(bytes);
            post.setEntity(new ByteArrayEntity(bytes));

HttpPost 的参数在哪里写呢?

【问题讨论】:

    标签: java http-post apache-httpcomponents


    【解决方案1】:

    在处理文件上传时,您必须使用MultipartEntityFileBody

    例子:

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("someparameter1", new StringBody("Woody"));
    entity.addPart("someparameter2", new StringBody("Woodpecker"));
    File fileToSend = new File(filePath);
    FileBody fileBody = new FileBody(fileToSend, "application/octet-stream");
    entity.addPart("upload_file", fileBody);
    
    httpPost.setEntity(entity);
    

    使用MultipartEntityBuilder - 尝试关注:

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    
    final File aFile = new File(fileName);
    FileBody fileBody = new FileBody(file);
    
    builder.addPart("file", fileBody);  
    builder.addTextBody("requestId", requestId);
    final HttpEntity httpEntity = builder.build();
    

    【讨论】:

    • 谢谢。我试过这个HttpEntity entity = MultipartEntityBuilder.create() .addTextBody("requestId", requestId, ContentType.TEXT_PLAIN) .addBinaryBody("myfile", bytes, ContentType.DEFAULT_BINARY, fileName).build(); post.setEntity(entity); 仍然不起作用,因为服务器无法识别 requestId 参数。使用 url 传递参数确实有效。喜欢:String uri = url + "&amp;requestId=" + requestId;.
    猜你喜欢
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    相关资源
    最近更新 更多