HttpClient--Multipart Request

这里主要记录一下如何使用HttpClient来发送Multipart Request

The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better performance and more flexibility.

HttpClient官方网站
HttpComponents包括三个模块:HttpCore、HttpClient、Asynch HttpClient

    其中HttpCore是低层级的Http通信元件,用于实现自定义的客户端和服务端的HTTP通信服务。HTTPCore支持BIO和NIO两种IO模式。其中BIO,也就是阻塞IO适用于数据密集型低延迟场景;NIO适用于数据吞吐量的重要性低于高并发的高延迟场景。

    HTTPClient是基于HttpCore的兼容HTTP/1.1的代理实现,它还支持客户端身份验证,HTTP状态管理,HTTP连接管理。

    Asynch HTTPClient是HttpClient的补充,适用于处理高并发的情况。

HttpClient发送Multipart Request

/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * .
 *
 */
package org.apache.http.examples.entity.mime;

import java.io.File;

import org.apache.http.HttpEntity;
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.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

一般步骤

step1. 获取HttpClient实例 HttpClient httpClient = HttpClients.createDefault();
step2. 建立HttpPost连接
step3. 设置Post Entity
step4. HttpClient execute post
step5. 获取response
step6. 获取response entity
    注意其中的设置POST Entity,有几个xxxBody,这几个类来自于Apache提供的package:
org.apache.http.entity.mime.content
其中包含以下四种Body:
ByteArrayBody Binary body part backed by a byte array.
FileBody Binary body part backed by a file.
InputStreamBody Binary body part backed by an input stream.
StringBody Text body part backed by a byte array.
    我们可以根据具体情况来选择要往Post中添加,如果有多个文件则每个文件都要addPart一次,其实HTTPEntity有很多的实现提供了类似于addBinaryBody、addStringBody这样的方法,针对性更强。

你可能感兴趣的:(HttpClient--Multipart Request)