使用OkHttp上傳文件

使用OkHttp,用multipart/form-data的形式上傳文件。java

OkHttp版本:3.6.0post

package com.neusoft.micia.util.http;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * http client。
 */
public class HttpClient {

    protected final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    OkHttpClient httpClient = new OkHttpClient().newBuilder()
            .readTimeout(5000, TimeUnit.MILLISECONDS)
            .build();

    /**
     * 上傳文件。
     * @param formFields 表單信息
     * @param files 文件信息
     */
    public void postMultipart(String url, Map<String, String> formFields, File[] files) throws Exception {

        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        for (Map.Entry<String, String> field: formFields.entrySet()) { // 添加表單信息
            bodyBuilder.addFormDataPart(field.getKey(), field.getValue());
        }
        MediaType mediaType = MediaType.parse("text/plain");
        for (File file: files) { // 添加文件
            bodyBuilder.addFormDataPart("files", file.getName(),
                    RequestBody.create(mediaType, file));
        }

        Request request = new Request.Builder()
                .url(url)
                .post(bodyBuilder.build())
                .build();
        try (Response response = httpClient.newCall(request).execute()) {
            if ( response.isSuccessful() ) {
                // TODO handle response if needed
            } else {
                throw new java.lang.IllegalStateException("Not [200..300) range code response [" + response.toString() + "]");
            }
        } catch (IOException e) {
            log.error("Http error [" + request.toString() + "]", e);
            throw e;
        }
    }
}
相關文章
相關標籤/搜索