Search in sources :

Example 6 with HttpParams

use of com.lzy.okgo.model.HttpParams in project okhttp-OkGo by jeasonlzy.

the class HttpUtils method generateMultipartRequestBody.

/**
 * 生成类似表单的请求体
 */
public static RequestBody generateMultipartRequestBody(HttpParams params, boolean isMultipart) {
    if (params.fileParamsMap.isEmpty() && !isMultipart) {
        // 表单提交,没有文件
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        for (String key : params.urlParamsMap.keySet()) {
            List<String> urlValues = params.urlParamsMap.get(key);
            for (String value : urlValues) {
                bodyBuilder.addEncoded(key, value);
            }
        }
        return bodyBuilder.build();
    } else {
        // 表单提交,有文件
        MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        // 拼接键值对
        if (!params.urlParamsMap.isEmpty()) {
            for (Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()) {
                List<String> urlValues = entry.getValue();
                for (String value : urlValues) {
                    multipartBodybuilder.addFormDataPart(entry.getKey(), value);
                }
            }
        }
        // 拼接文件
        for (Map.Entry<String, List<HttpParams.FileWrapper>> entry : params.fileParamsMap.entrySet()) {
            List<HttpParams.FileWrapper> fileValues = entry.getValue();
            for (HttpParams.FileWrapper fileWrapper : fileValues) {
                RequestBody fileBody = RequestBody.create(fileWrapper.contentType, fileWrapper.file);
                multipartBodybuilder.addFormDataPart(entry.getKey(), fileWrapper.fileName, fileBody);
            }
        }
        return multipartBodybuilder.build();
    }
}
Also used : FormBody(okhttp3.FormBody) HttpParams(com.lzy.okgo.model.HttpParams) MultipartBody(okhttp3.MultipartBody) List(java.util.List) FileNameMap(java.net.FileNameMap) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Aggregations

HttpParams (com.lzy.okgo.model.HttpParams)6 HttpHeaders (com.lzy.okgo.model.HttpHeaders)4 List (java.util.List)2 Map (java.util.Map)2 FormBody (okhttp3.FormBody)2 MultipartBody (okhttp3.MultipartBody)2 RequestBody (okhttp3.RequestBody)2 CookieJarImpl (com.lzy.okgo.cookie.CookieJarImpl)1 DBCookieStore (com.lzy.okgo.cookie.store.DBCookieStore)1 PersistentCookieStore (com.lzy.okgo.cookie.store.PersistentCookieStore)1 HttpsUtils (com.lzy.okgo.https.HttpsUtils)1 HttpLoggingInterceptor (com.lzy.okgo.interceptor.HttpLoggingInterceptor)1 FileNameMap (java.net.FileNameMap)1 CertificateException (java.security.cert.CertificateException)1 OkHttpClient (okhttp3.OkHttpClient)1