Java 类com.squareup.okhttp.MultipartBuilder 实例源码

项目:boohee_v5.6    文件:Client.java   
private void asyncMultipartPost(String url, StringMap fields, ProgressHandler
        progressHandler, String fileName, RequestBody file, CompletionHandler
        completionHandler, CancellationHandler cancellationHandler) {
    if (this.converter != null) {
        url = this.converter.convert(url);
    }
    final MultipartBuilder mb = new MultipartBuilder();
    mb.addFormDataPart("file", fileName, file);
    fields.forEach(new Consumer() {
        public void accept(String key, Object value) {
            mb.addFormDataPart(key, value.toString());
        }
    });
    mb.type(MediaType.parse("multipart/form-data"));
    RequestBody body = mb.build();
    if (progressHandler != null) {
        body = new CountingRequestBody(body, progressHandler, cancellationHandler);
    }
    asyncSend(new Builder().url(url).post(body), null, completionHandler);
}
项目:ktball    文件:OkHttpUploadRequest.java   
private void addParams(MultipartBuilder builder, Map<String, String> params)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
项目:ktball    文件:OkHttpUploadRequest.java   
@Override
public RequestBody buildRequestBody()
{
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null)
    {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++)
        {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
项目:meishiDemo    文件:OkHttpUploadRequest.java   
private void addParams(MultipartBuilder builder, Map<String, String> params)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
项目:meishiDemo    文件:OkHttpUploadRequest.java   
@Override
public RequestBody buildRequestBody()
{
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null)
    {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++)
        {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
项目:JOSM-IndoorEditor    文件:RequestExecutor.java   
public static String callGTMC(String url, String filepath) {
    try {
        // ---
        File zipFile = new File(filepath);

        // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
        RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("zipFile", zipFile.getName(), RequestBody.create(MEDIA_TYPE_ZIP, zipFile)).build();
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException("Unexpected code " + response);

        return response.body().string();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}
项目:AyoSunny    文件:XgoHttpClient.java   
/**
 * 初始化Body类型请求参数
 * init Body type params
 */
private RequestBody initRequestBody(TreeMap<String , Object> params) {
    MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    Set<Map.Entry<String, Object>> entries = params.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (value instanceof File) {
            File file = (File) value;
            try {
                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                String mimeType = fileNameMap.getContentTypeFor(file.getAbsolutePath());
                XgoLog.w("mimeType::" + mimeType);
                bodyBuilder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(mimeType), file));
            } catch (Exception e) {
                e.printStackTrace();
                XgoLog.e("mimeType is Error !");
            }
        } else {
            XgoLog.w(key + "::" + value);
            bodyBuilder.addFormDataPart(key, value.toString());
        }
    }
    return bodyBuilder.build();
}
项目:QiNiuGenertorToken    文件:Client.java   
private Response multipartPost(String url,
                               StringMap fields,
                               String name,
                               String fileName,
                               RequestBody file,
                               StringMap headers) throws QiniuException {
    final MultipartBuilder mb = new MultipartBuilder();
    mb.addFormDataPart(name, fileName, file);

    fields.forEach(new StringMap.Consumer() {
        @Override
        public void accept(String key, Object value) {
            mb.addFormDataPart(key, value.toString());
        }
    });
    mb.type(MediaType.parse("multipart/form-data"));
    RequestBody body = mb.build();
    Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
    return send(requestBuilder, headers);
}
项目:Mobile-Office    文件:RequestFactory.java   
private static Request buildUpload(ACTION action, File[] files,
        String[] filenames, Object requestBean) {
    String json = GsonTool.toJson(requestBean);
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    if (files != null) {
        for (int i = 0; i < filenames.length; i++) {
            builder.addPart(Headers.of("Content-Disposition",
                    "form-data;name=\"" + "file" + i + "\";filename=\""
                            + filenames[i] + "\""), RequestBody.create(
                    MediaType.parse("application/octet-stream"), files[i]));
        }
    }
    builder.addPart(
            Headers.of("Content-Disposition", "form-data; name=\""
                    + RequestArr.requestArg + "\""),
            RequestBody.create(null, json));
    String url = RequestArr.mainUrl + RequestArr.mUrls.get(action);
    return new Request.Builder().url(url).post(builder.build()).build();
}
项目:KwPresent    文件:DownLoadManager.java   
private Request buildMultipartFormRequest(String url, String[] fileKeys, File[] files, Param[] paramses) {
    paramses = validateParam(paramses);
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

    for (Param param : paramses) {
        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, param.value));
    }

    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMineType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody);
        }
    }

    RequestBody requestBody = builder.build();
    return new Request.Builder().url(url).post(requestBody).build();
}
项目:moment-for-android-wear    文件:RxMomentApi.java   
private String uploadDrawingBitmap(String uploadUrl, Bitmap drawing) throws IOException, JSONException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    drawing.compress(Bitmap.CompressFormat.PNG, 0, bos);

    RequestBody value = RequestBody.create(MediaType.parse("image/png"), bos.toByteArray());
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("moment", "moment.png", value)
            .build();

    Request request = new Request.Builder()
            .url(uploadUrl)
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        JSONObject resultJson = new JSONObject(response.body().string());
        return resultJson.getString("blob-key");
    } else {
        throw new IOException("Unexpected code " + response);
    }
}
项目:android-kit-old    文件:OkHttpUploadRequest.java   
@Override
public RequestBody buildRequestBody() {
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
项目:OkHttpTutorial    文件:OkHttpUtil.java   
private RequestBody buildMultipartFormRequest(String[] fileKeys, File[] files, Map<String, String> params) {
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.addPart(Headers.of("Content-Disposition", "form-data;name=\"" + entry.getKey() + "\""), RequestBody.create(null, entry.getValue()));
    }
    if (files != null && fileKeys != null && files.length == fileKeys.length) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            fileBody = RequestBody.create(MediaType.parse(getMimeType(files[i].getName())), files[i]);
            builder.addPart(Headers.of("Content-Disposition",
                    "form-data;name=\"" + fileKeys[i] + "\";filename=\"" + files[i].getName() + "\""), fileBody);
        }
    } else {
        try {
            throw new Exception("文件名参数长度和文件实体内容长度不一致");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return builder.build();
}
项目:meiShi    文件:OkHttpUploadRequest.java   
private void addParams(MultipartBuilder builder, Map<String, String> params)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
项目:meiShi    文件:OkHttpUploadRequest.java   
@Override
public RequestBody buildRequestBody()
{
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null)
    {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++)
        {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
项目:okhttp-utils    文件:OkHttpUploadRequest.java   
private void addParams(MultipartBuilder builder, Map<String, String> params)
{
    if (builder == null)
    {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
项目:okhttp-utils    文件:OkHttpUploadRequest.java   
@Override
public RequestBody buildRequestBody()
{
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null)
    {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++)
        {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
项目:Chute-SDK-V2-Android    文件:BaseUploadRequest.java   
public BaseUploadRequest(String filePath,
        UploadProgressListener uploadListener,
        HttpCallback<ListResponseModel<AssetModel>> callback) {

    this.uploadListener = uploadListener;
    this.file = new File(filePath);
    this.requestBody = new CountingFileRequestBody(file, MediaTypes.OCTET_STREAM, this);
    RequestBody requestBody = new MultipartBuilder()
        .type(MultipartBuilder.FORM)
        .addFormDataPart(getMultipartEntityKey(), file.getName(), this.requestBody)
        .build();
    setRequestMethod(RequestMethod.POST, requestBody);
    setCallback(callback);
    setParser(new ListResponseParser<AssetModel>(AssetModel.class));
    setRequestOptions(new RequestOptions.RequestOptionsBuilder().setRunInSingleThread(true).build());
}
项目:Logistics-guard    文件:OkHttpClientManager.java   
private Request buildMultipartFormRequest(String url, File[] files,
                                          String[] fileKeys, Param[] params) {
    params = validateParam(params);

    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);

    for (Param param : params) {
        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                RequestBody.create(null, param.value));
    }
    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            //TODO 根据文件名设置contentType
            builder.addPart(Headers.of("Content-Disposition",
                    "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    RequestBody requestBody = builder.build();
    return new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
}
项目:boohee_v5.6    文件:bu.java   
public void b(File file, cw cwVar, OnFailureCallBack onFailureCallBack) {
    file.exists();
    a(new Builder().url("https://eco-api-upload.meiqia.com/upload").post(new MultipartBuilder
            ().type(MultipartBuilder.FORM).addFormDataPart("file", "file.amr", RequestBody
            .create(MediaType.parse("audio/amr"), file)).build()).build(), new cs(this,
            cwVar), onFailureCallBack);
}
项目:mohoo-wechat-card    文件:OkHttpUtil.java   
public static String doPostImgHttpRequest(String url, File file)
        throws IOException {
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("buffer", file.getName(),
                    RequestBody.create(MEDIA_TYPE_PNG, file)).build();
    Request request = new Request.Builder().url(url).post(requestBody)
            .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        System.out.println("服务端错误:" + response);
        throw new IOException("Unexpected code " + response);
    }
    return response.body().string();
}
项目:NewsMe    文件:PostFormRequest.java   
private void addParams(MultipartBuilder builder)
{
    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));
        }
    }
}
项目:jstuart    文件:MMBot.java   
public MFileUpload uploadFile(String teamId, String channelId, File file) throws IOException {
    String url = host + "api/v3/teams/" + teamId + "/files/upload";
    MultipartBuilder bodyBuilder = new MultipartBuilder().type(MediaType.parse("multipart/form-data"))
            .addFormDataPart("channel_id", channelId).addFormDataPart("files", file.getName(),
                    RequestBody.create(MediaType.parse("application/octet-stream"), file));
    Request r = auth(new Request.Builder()).url(url).post(bodyBuilder.build()).build();
    Response response = client.newCall(r).execute();
    try (ResponseBody body = response.body()) {
        if (response.isSuccessful()) {
            MFileUpload files = gson.fromJson(body.string(), MFileUpload.class);
            return files;
        }
    }
    return null;
}
项目:Emojier-Andriod    文件:HttpPostRequest.java   
private RequestBody getRequestBody(Map<String, T> formParams) {
    MultipartBuilder multiBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (Map.Entry<String,T> entry : formParams.entrySet()) {
        String key = entry.getKey();
        T value = entry.getValue();
        if (value instanceof String) {
            multiBuilder.addFormDataPart(key, String.valueOf(value));
        }else if (value instanceof File){
            multiBuilder.addPart(
                    Headers.of("Content-Disposition", "form-data;name=\"emoji\"; filename=\"" + key + "\""),
                    RequestBody.create(MEDIA_TYPE_STREAM, (File) value));
        }
    }
    return multiBuilder.build();
}
项目:mohoo-wechat-pay    文件:OkHttpUtil.java   
public static String doPostImgHttpRequest(String url, File file)
        throws IOException {
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("buffer", file.getName(),
                    RequestBody.create(MEDIA_TYPE_PNG, file)).build();
    Request request = new Request.Builder().url(url)
            .post(requestBody).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        System.out.println("服务端错误:" + response);
        throw new IOException("Unexpected code " + response);
    }
    return response.body().string();
}
项目:AndroidGeek    文件:OkHttpClientManager.java   
private Request buildMultipartFormRequest(String url, File[] files,
                                          String[] fileKeys, Param[] params, Object tag) {
    params = validateParam(params);

    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);

    for (Param param : params) {
        builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                RequestBody.create(null, param.value));
    }
    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            // TODO 根据文件名设置contentType
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    RequestBody requestBody = builder.build();
    return new Request.Builder()
            .url(url)
            .post(requestBody)
            .tag(tag)
            .build();
}
项目:AndNet    文件:OkHttpStack.java   
@Override
public void post(final String url, final RequestParams params,
                 final Net.Parser<T> parser,
                 final Net.Callback<T> callback,
                 final Object tag) {
    MultipartBuilder builder = createRequestBody(params);
    Request request = new Request.Builder()
            .url(url).post(builder.build()).build();
    call(request, parser, callback, tag);
}
项目:AndNet    文件:OkHttpStack.java   
@Override
public void put(final String url, final RequestParams params,
                final Net.Parser<T> parser,
                final Net.Callback<T> callback,
                final Object tag) {
    MultipartBuilder builder = createRequestBody(params);
    Request request = new Request.Builder()
            .url(url).put(builder.build()).build();
    call(request, parser, callback, tag);
}
项目:android-kit-old    文件:OkHttpUploadRequest.java   
private void addParams(MultipartBuilder builder, Map<String, String> params) {
    if (builder == null) {
        throw new IllegalArgumentException("builder can not be null .");
    }

    if (params != null && !params.isEmpty()) {
        for (String key : params.keySet()) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                    RequestBody.create(null, params.get(key)));

        }
    }
}
项目:CouldBooks    文件:OkHttpClientManager.java   
private Request buildMultipartFormRequest(String url, File[] files,
        String[] fileKeys, Param[] params) {
    params = validateParam(params);

    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);

    for (Param param : params) {
        builder.addPart(
                Headers.of("Content-Disposition", "form-data; name=\""
                        + param.key + "\""),
                RequestBody.create(null, param.value));
    }
    if (files != null) {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String fileName = file.getName();
            fileBody = RequestBody.create(
                    MediaType.parse(guessMimeType(fileName)), file);
            // TODO 根据文件名设置contentType
            builder.addPart(
                    Headers.of("Content-Disposition", "form-data; name=\""
                            + fileKeys[i] + "\"; filename=\"" + fileName
                            + "\""), fileBody);
        }
    }

    RequestBody requestBody = builder.build();
    return new Request.Builder().url(url).post(requestBody).build();
}
项目:Bugtags-Android    文件:Okhttp2Test.java   
public static void postMultipart(Activity activity) {
    String urlStr = HOST_PREFIX + "/post/multer";

    //bitmap
    Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

    //attachment
    String attachmentName = "bitmap";
    String attachmentFileName = "bitmap.png";

    RequestBody body = new MultipartBuilder().
            type(MultipartBuilder.FORM).
            addFormDataPart(attachmentName, attachmentFileName, RequestBody.create(MediaType.parse("image/png"), stream.toByteArray())).
            build();

    Request request = new Request.Builder().
            url(urlStr).post(body).
            addHeader("a", "b").
            addHeader("b", "c").
            build();

    try {
        Response response = okHttpClient.newCall(request).execute();
        Log.d(TAG, response.body().string());

    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:cannon    文件:MultipartRequest.java   
private void build(final Map<String, String> params, final Map<String, Pair<File, String>> files) {
    MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

    for (Map.Entry<String, Pair<File, String>> filePart : files.entrySet()) {
        Pair<File, String> filePair = filePart.getValue();

        File file = filePair.first;
        String mediaType = filePair.second;

        multipartBuilder.addFormDataPart(
                filePart.getKey(),
                file.getName(),
                RequestBody.create(MediaType.parse(mediaType), file)
        );
    }

    if (params != null) {
        for (Map.Entry<String, String> stringPart : params.entrySet()) {
            multipartBuilder.addFormDataPart(
                    stringPart.getKey(),
                    stringPart.getValue()
            );
        }
    }

    mRequestBody = multipartBuilder.build();
}
项目:api-java-client    文件:RestClient.java   
public Response multipartPost(final String url, final String bodyName, final String body,
    final String fileName, final File file)
{
    OkHttpClient multipartClient = client.clone();

    try
    {
        RequestBody jsonPart =
            RequestBody.create(MediaType.parse("text/plain; charset=UTF-8"), body);
        RequestBody filePart =
            RequestBody.create(MediaType.parse("application/octet-stream; charset=ISO-8859-1"),
                file);
        RequestBody requestBody =
            new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"" + bodyName + "\""),
                    jsonPart) //
                .addFormDataPart(fileName, file.getName(), filePart) //
                .build();
        Request request = new Request.Builder().url(absolute(url)).post(requestBody) //
            .build();
        Response response = multipartClient.newCall(request).execute();
        checkResponse(request, response, response.body().string());

        return response;
    }
    catch (IOException ex)
    {
        throw Throwables.propagate(ex);
    }
}
项目:boohee_v5.6    文件:bu.java   
public void a(File file, cw cwVar, OnFailureCallBack onFailureCallBack) {
    a(new Builder().url("https://eco-api-upload.meiqia.com/upload").post(new MultipartBuilder
            ().type(MultipartBuilder.FORM).addFormDataPart("file", "file.jpeg", RequestBody
            .create(MediaType.parse("image/jpeg"), file)).build()).build(), new cr(this,
            cwVar), onFailureCallBack);
}
项目:ReactNativeSignatureExample    文件:NetworkingModule.java   
private
@Nullable
MultipartBuilder constructMultipartBody(
    ExecutorToken ExecutorToken,
    ReadableArray body,
    String contentType,
    int requestId) {
  MultipartBuilder multipartBuilder = new MultipartBuilder();
  multipartBuilder.type(MediaType.parse(contentType));

  for (int i = 0, size = body.size(); i < size; i++) {
    ReadableMap bodyPart = body.getMap(i);

    // Determine part's content type.
    ReadableArray headersArray = bodyPart.getArray("headers");
    Headers headers = extractHeaders(headersArray, null);
    if (headers == null) {
      onRequestError(
          ExecutorToken,
          requestId,
          "Missing or invalid header format for FormData part.");
      return null;
    }
    MediaType partContentType = null;
    String partContentTypeStr = headers.get(CONTENT_TYPE_HEADER_NAME);
    if (partContentTypeStr != null) {
      partContentType = MediaType.parse(partContentTypeStr);
      // Remove the content-type header because MultipartBuilder gets it explicitly as an
      // argument and doesn't expect it in the headers array.
      headers = headers.newBuilder().removeAll(CONTENT_TYPE_HEADER_NAME).build();
    }

    if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) {
      String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING);
      multipartBuilder.addPart(headers, RequestBody.create(partContentType, bodyValue));
    } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) {
      if (partContentType == null) {
        onRequestError(
            ExecutorToken,
            requestId,
            "Binary FormData part needs a content-type header.");
        return null;
      }
      String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI);
      InputStream fileInputStream =
          RequestBodyUtil.getFileInputStream(getReactApplicationContext(), fileContentUriStr);
      if (fileInputStream == null) {
        onRequestError(
            ExecutorToken,
            requestId,
            "Could not retrieve file for uri " + fileContentUriStr);
        return null;
      }
      multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream));
    } else {
      onRequestError(ExecutorToken, requestId, "Unrecognized FormData part.");
    }
  }
  return multipartBuilder;
}
项目:ReactNativeSignatureExample    文件:NetworkingModuleTest.java   
@Test
public void testMultipartPostRequestSimple() throws Exception {
  PowerMockito.mockStatic(RequestBodyUtil.class);
  when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
      .thenReturn(mock(InputStream.class));
  when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
      .thenReturn(mock(RequestBody.class));

  JavaOnlyMap body = new JavaOnlyMap();
  JavaOnlyArray formData = new JavaOnlyArray();
  JavaOnlyMap bodyPart = new JavaOnlyMap();
  bodyPart.putString("string", "value");
  bodyPart.putArray(
      "headers",
      JavaOnlyArray.from(
          Arrays.asList(
              JavaOnlyArray.of("content-disposition", "name"))));
  formData.pushMap(bodyPart);
  body.putArray("formData", formData);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });

  NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);
  networkingModule.sendRequest(
    mock(ExecutorToken.class),
    "POST",
    "http://someurl/uploadFoo",
    0,
    new JavaOnlyArray(),
    body,
    true,
    0);

  // verify url, method, headers
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo");
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).
      isEqualTo(MultipartBuilder.FORM.type());
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).
      isEqualTo(MultipartBuilder.FORM.subtype());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(1);
}
项目:ReactNativeSignatureExample    文件:NetworkingModuleTest.java   
@Test
public void testMultipartPostRequestHeaders() throws Exception {
  PowerMockito.mockStatic(RequestBodyUtil.class);
  when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
      .thenReturn(mock(InputStream.class));
  when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
      .thenReturn(mock(RequestBody.class));

  List<JavaOnlyArray> headers = Arrays.asList(
          JavaOnlyArray.of("Accept", "text/plain"),
          JavaOnlyArray.of("User-Agent", "React test agent/1.0"),
          JavaOnlyArray.of("content-type", "multipart/form-data"));

  JavaOnlyMap body = new JavaOnlyMap();
  JavaOnlyArray formData = new JavaOnlyArray();
  JavaOnlyMap bodyPart = new JavaOnlyMap();
  bodyPart.putString("string", "value");
  bodyPart.putArray(
      "headers",
      JavaOnlyArray.from(
          Arrays.asList(
              JavaOnlyArray.of("content-disposition", "name"))));
  formData.pushMap(bodyPart);
  body.putArray("formData", formData);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });

  NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);
  networkingModule.sendRequest(
    mock(ExecutorToken.class),
    "POST",
    "http://someurl/uploadFoo",
    0,
    JavaOnlyArray.from(headers),
    body,
    true,
    0);

  // verify url, method, headers
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo");
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).
      isEqualTo(MultipartBuilder.FORM.type());
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).
      isEqualTo(MultipartBuilder.FORM.subtype());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(3);
  assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain");
  assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0");
  assertThat(requestHeaders.get("content-type")).isEqualTo("multipart/form-data");
}
项目:react-native-ibeacon-android    文件:NetworkingModule.java   
private
@Nullable
MultipartBuilder constructMultipartBody(
    ExecutorToken ExecutorToken,
    ReadableArray body,
    String contentType,
    int requestId) {
  MultipartBuilder multipartBuilder = new MultipartBuilder();
  multipartBuilder.type(MediaType.parse(contentType));

  for (int i = 0, size = body.size(); i < size; i++) {
    ReadableMap bodyPart = body.getMap(i);

    // Determine part's content type.
    ReadableArray headersArray = bodyPart.getArray("headers");
    Headers headers = extractHeaders(headersArray, null);
    if (headers == null) {
      onRequestError(
          ExecutorToken,
          requestId,
          "Missing or invalid header format for FormData part.");
      return null;
    }
    MediaType partContentType = null;
    String partContentTypeStr = headers.get(CONTENT_TYPE_HEADER_NAME);
    if (partContentTypeStr != null) {
      partContentType = MediaType.parse(partContentTypeStr);
      // Remove the content-type header because MultipartBuilder gets it explicitly as an
      // argument and doesn't expect it in the headers array.
      headers = headers.newBuilder().removeAll(CONTENT_TYPE_HEADER_NAME).build();
    }

    if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) {
      String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING);
      multipartBuilder.addPart(headers, RequestBody.create(partContentType, bodyValue));
    } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) {
      if (partContentType == null) {
        onRequestError(
            ExecutorToken,
            requestId,
            "Binary FormData part needs a content-type header.");
        return null;
      }
      String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI);
      InputStream fileInputStream =
          RequestBodyUtil.getFileInputStream(getReactApplicationContext(), fileContentUriStr);
      if (fileInputStream == null) {
        onRequestError(
            ExecutorToken,
            requestId,
            "Could not retrieve file for uri " + fileContentUriStr);
        return null;
      }
      multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream));
    } else {
      onRequestError(ExecutorToken, requestId, "Unrecognized FormData part.");
    }
  }
  return multipartBuilder;
}
项目:react-native-ibeacon-android    文件:NetworkingModuleTest.java   
@Test
public void testMultipartPostRequestSimple() throws Exception {
  PowerMockito.mockStatic(RequestBodyUtil.class);
  when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
      .thenReturn(mock(InputStream.class));
  when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
      .thenReturn(mock(RequestBody.class));

  JavaOnlyMap body = new JavaOnlyMap();
  JavaOnlyArray formData = new JavaOnlyArray();
  JavaOnlyMap bodyPart = new JavaOnlyMap();
  bodyPart.putString("string", "value");
  bodyPart.putArray(
      "headers",
      JavaOnlyArray.from(
          Arrays.asList(
              JavaOnlyArray.of("content-disposition", "name"))));
  formData.pushMap(bodyPart);
  body.putArray("formData", formData);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });

  NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);
  networkingModule.sendRequest(
    mock(ExecutorToken.class),
    "POST",
    "http://someurl/uploadFoo",
    0,
    new JavaOnlyArray(),
    body,
    true,
    0);

  // verify url, method, headers
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo");
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).
      isEqualTo(MultipartBuilder.FORM.type());
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).
      isEqualTo(MultipartBuilder.FORM.subtype());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(1);
}
项目:react-native-ibeacon-android    文件:NetworkingModuleTest.java   
@Test
public void testMultipartPostRequestHeaders() throws Exception {
  PowerMockito.mockStatic(RequestBodyUtil.class);
  when(RequestBodyUtil.getFileInputStream(any(ReactContext.class), any(String.class)))
      .thenReturn(mock(InputStream.class));
  when(RequestBodyUtil.create(any(MediaType.class), any(InputStream.class)))
      .thenReturn(mock(RequestBody.class));

  List<JavaOnlyArray> headers = Arrays.asList(
          JavaOnlyArray.of("Accept", "text/plain"),
          JavaOnlyArray.of("User-Agent", "React test agent/1.0"),
          JavaOnlyArray.of("content-type", "multipart/form-data"));

  JavaOnlyMap body = new JavaOnlyMap();
  JavaOnlyArray formData = new JavaOnlyArray();
  JavaOnlyMap bodyPart = new JavaOnlyMap();
  bodyPart.putString("string", "value");
  bodyPart.putArray(
      "headers",
      JavaOnlyArray.from(
          Arrays.asList(
              JavaOnlyArray.of("content-disposition", "name"))));
  formData.pushMap(bodyPart);
  body.putArray("formData", formData);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(
      new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });

  NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient);
  networkingModule.sendRequest(
    mock(ExecutorToken.class),
    "POST",
    "http://someurl/uploadFoo",
    0,
    JavaOnlyArray.from(headers),
    body,
    true,
    0);

  // verify url, method, headers
  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://someurl/uploadFoo");
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).
      isEqualTo(MultipartBuilder.FORM.type());
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).
      isEqualTo(MultipartBuilder.FORM.subtype());
  Headers requestHeaders = argumentCaptor.getValue().headers();
  assertThat(requestHeaders.size()).isEqualTo(3);
  assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain");
  assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0");
  assertThat(requestHeaders.get("content-type")).isEqualTo("multipart/form-data");
}