Beispiel #1
0
  public void postAction() {
    onEvent(this, AnaticsManager.EVENT.CLICK, "postAction");
    MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    builder.addFormDataPart("Score", "33");
    builder.addFormDataPart("PlayerName", "wqr");
    HttpRequester.post(
        new RequestCallBack() {

          @Override
          public void _onStart() {
            textView.append("onStart...\n");
            LoadViewManager.addLargeView(self());
          }

          @Override
          protected void _onFinish() {
            textView.append("onFinish...\n");
            LoadViewManager.hideLargeView();
          }

          @Override
          public void _onFailure(final IOException e) {
            textView.append(Html.fromHtml(String.format("Throwable=%s", e) + "\n"));
          }

          @Override
          public void _onResponse(String response) {
            textView.append(response + "\n");
          }
        },
        URL,
        builder.build());
  }
  @Override
  public void post(
      String url,
      RequestParams params,
      Net.Parser<T> parser,
      Net.Callback<T> callback,
      Object tag) {
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    // 添加普通的参数
    LinkedHashMap<String, String> map = params.get();
    for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
      String key = iterator.next();
      builder.addPart(
          Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
          RequestBody.create(null, map.get(key)));
    }
    // 添加文件参数
    LinkedHashMap<String, File> files = params.files();
    for (Iterator<String> iterator = files.keySet().iterator(); iterator.hasNext(); ) {
      String key = iterator.next();
      File file = files.get(key);
      builder.addPart(
          Headers.of(
              "Content-Disposition",
              "form-data; name=\"" + key + "\";filename=\"" + file.getName() + "\""),
          RequestBody.create(MediaType.parse("application/octet-stream"), file));
    }

    // 组装Request
    Request request = new Request.Builder().url(url).post(builder.build()).build();
    call(request, parser, callback, tag);
  }
Beispiel #3
0
    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();
    }
  private void uploadRecord(String id) {
    String[] key = {"cmd", "userno", "fileno", "togetherid"};
    String[] value = {"uploadappointinstallsound", userNo, orderId, id};

    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    for (int i = 0; i < key.length; i++) {
      builder.addFormDataPart(key[i], value[i]);
    }

    String fileName = recordFile.getName();
    RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), recordFile);
    builder.addFormDataPart("", fileName, fileBody);

    HttpUtils.sendHttpPostRequest(
        builder.build(),
        new HttpCallbackListener() {
          @Override
          public void onFinish(final String response) {
            Log.e("responseVoice", response);
            handler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    if (response.substring(0, 1).equals("E")) {
                      ToastUtil.showToast(DistributeActivity.this, "上传录音失败", Toast.LENGTH_SHORT);
                      pDialog.dismiss();
                    } else {
                      recordFile.delete();
                      recordFile = null;
                      saveInfo(response);
                    }
                  }
                });
          }

          @Override
          public void onError(Exception e) {
            handler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    ToastUtil.showToast(DistributeActivity.this, "与服务器断开连接", Toast.LENGTH_SHORT);
                    pDialog.dismiss();
                  }
                });
          }
        });
  }
Beispiel #5
0
  // post with file
  public static void asyncPost(String url, Map<String, String> body, File file, Callback callback) {

    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MultipartBuilder.MIXED);

    for (String key : body.keySet()) {
      multipartBuilder.addFormDataPart(key, body.get(key));
    }
    Date date = new Date();
    if (file != null && file.exists()) {
      ////            //图片处理
      //        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
      //        bitmapOptions.inSampleSize = 3;
      //        bitmapOptions.inPreferredConfig= Bitmap.Config.RGB_565;
      //
      ////            //Bitmap cameraBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),
      // bitmapOptions);
      //        Bitmap cameraBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),
      // bitmapOptions);
      //
      //        /**
      //         * 把图片旋转为正的方向
      //         */
      //        Bitmap bitmap =
      // ImageTools.rotaingImageView(ImageTools.readPictureDegree(file.getAbsolutePath()),
      // cameraBitmap);
      //        date1 = new Date();
      ////          byte[] bytes = Bitmap2Bytes(bitmap);
      //
      //        FileTools.createDirs("萌宝派");
      //        File sendFile = new
      // File(Environment.getExternalStorageDirectory().getAbsoluteFile(), File.separator + "萌宝派" +
      // File.separator + file.getName());
      //        boolean b = ImageTools.saveBitmap(bitmap, sendFile.getAbsolutePath());
      //        //图片处理
      //        if (b) {
      //            multipartBuilder.addFormDataPart("image", "image",
      // RequestBody.create(MEDIA_TYPE_PNG, sendFile));
      //            Log.i(TAG, "add picture addres = " + sendFile.getAbsolutePath());
      //        }
      multipartBuilder.addFormDataPart(
          "image", "image", RequestBody.create(MEDIA_TYPE_PNG, getSmallBitmap(file.getPath())));
    }
    RequestBody formBody = multipartBuilder.build();
    Request request = new Request.Builder().url(url).post(formBody).build();
    enqueue(request, callback);
  }
 /**
  * Build a multipart (file uploading) request body with the given form parameters, which could
  * contain text fields and file fields.
  *
  * @param formParams Form parameters in the form of Map
  * @return RequestBody
  */
 public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
   MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
   for (Entry<String, Object> param : formParams.entrySet()) {
     if (param.getValue() instanceof File) {
       File file = (File) param.getValue();
       Headers partHeaders =
           Headers.of(
               "Content-Disposition",
               "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
       MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
       mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
     } else {
       Headers partHeaders =
           Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
       mpBuilder.addPart(
           partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
     }
   }
   return mpBuilder.build();
 }
Beispiel #7
0
  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);
  }
  private void addPart(MultipartBuilder multipartBuilder, String key, Object o) {
    if (o == null) {
      return;
    }

    if (o instanceof File) {
      File tmp = (File) o;
      String extType = MimeTypeMap.getFileExtensionFromUrl(tmp.getAbsolutePath());
      String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extType);
      if (mimeType == null) {
        mimeType = MIME.get(extType.toLowerCase());
      }
      RequestBody file = RequestBody.create(MediaType.parse(mimeType), tmp);
      multipartBuilder.addFormDataPart(key, tmp.getName(), file);
      Timber.d("Media Type. %s, %s, %s", tmp, mimeType, file.contentType());
    } else if (o instanceof byte[]) {
      byte[] tmp = (byte[]) o;
      RequestBody file = RequestBody.create(MEDIA_TYPE_DEFAULT, tmp);
      multipartBuilder.addFormDataPart(key, byteDataId.incrementAndGet() + "", file);
      Timber.d("Media Type. byte[], %s", file.contentType());
    } else {
      multipartBuilder.addFormDataPart(key, o.toString());
    }
  }
Beispiel #9
0
  private void uploadPhoto(
      @Nullable String title, @Nullable String description, @NonNull String filePath) {
    final File file = new File(filePath);

    if (!FileUtil.isFileValid(file)) {
      LogUtil.w(TAG, "File is invalid, bailing");
      return;
    }

    LogUtil.v(TAG, "Received File to upload");
    ApiClient client = new ApiClient(Endpoints.UPLOAD.getUrl(), ApiClient.HttpRequest.POST);
    MediaType type;

    if (file.getAbsolutePath().endsWith("png")) {
      type = MediaType.parse("image/png");
    } else if (file.getAbsolutePath().endsWith("gif")) {
      type = MediaType.parse("image/gif");
    } else {
      type = MediaType.parse("image/jpeg");
    }

    MultipartBuilder builder =
        new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                Headers.of("Content-Disposition", "form-data; name=\"image\""),
                new ProgressRequestBody(file, type, this));

    builder.addPart(
        Headers.of("Content-Disposition", "form-data; name=\"type\""),
        RequestBody.create(null, "file"));

    if (!TextUtils.isEmpty(title)) {
      builder.addPart(
          Headers.of("Content-Disposition", "form-data; name=\"title\""),
          RequestBody.create(null, title));
    }

    if (!TextUtils.isEmpty(description)) {
      builder.addPart(
          Headers.of("Content-Disposition", "form-data; name=\"description\""),
          RequestBody.create(null, description));
    }

    RequestBody body = builder.build();

    try {
      if (mNotificationId <= 0) mNotificationId = file.hashCode();
      onUploadStarted();
      JSONObject json = client.doWork(body);
      int status = json.getInt(ApiClient.KEY_STATUS);

      if (status == ApiClient.STATUS_OK) {
        handleResponse(json.getJSONObject(ApiClient.KEY_DATA));
      } else {
        onUploadFailed(title, description, filePath, true);
      }
    } catch (IOException | JSONException e) {
      LogUtil.e(TAG, "Error uploading file", e);
      onUploadFailed(title, description, filePath, true);
    }
  }
Beispiel #10
0
 // post with files
 public static void asyncPost(
     String url, Map<String, String> body, ArrayList<String> files, Callback callback) {
   MultipartBuilder multipartBuilder = new MultipartBuilder();
   multipartBuilder.type(MultipartBuilder.MIXED);
   for (String key : body.keySet()) {
     multipartBuilder.addFormDataPart(key, body.get(key));
   }
   if (files != null && files.size() > 0) {
     //            if (files.size() > 10) {
     //                for (int i = 0; i < 10; i++) {
     //                    //图片处理
     //                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
     //                    bitmapOptions.inSampleSize = 8;
     //                    Bitmap cameraBitmap = BitmapFactory.decodeFile(files.get(i),
     // bitmapOptions);
     //                    /**
     //                     * 把图片旋转为正的方向
     //                     */
     //                    Bitmap bitmap =
     // ImageTools.rotaingImageView(ImageTools.readPictureDegree(files.get(i)), cameraBitmap);
     //
     //
     //                    FileTools.createDirs("萌宝派");
     //                    File sendFile = new
     // File(Environment.getExternalStorageDirectory().getAbsoluteFile(), File.separator + "萌宝派" +
     // File.separator + new File(files.get(i)).getName());
     //                    boolean b = ImageTools.saveBitmap(bitmap, sendFile.getAbsolutePath());
     //                    //图片处理
     //                    if (b) {
     //                        multipartBuilder.addFormDataPart("image" + i, "image" + i,
     // RequestBody.create(MEDIA_TYPE_PNG, sendFile));
     //                        Log.i(TAG, "add picture addres = " + files.get(i) + "image" + (i +
     // 1));
     //                    }
     //                }
     //            } else {
     for (int i = 0; i < files.size(); i++) {
       //                    //图片处理
       //                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
       //                    bitmapOptions.inSampleSize = 8;
       //                    Bitmap cameraBitmap = BitmapFactory.decodeFile(files.get(i),
       // bitmapOptions);
       //                    /**
       //                     * 把图片旋转为正的方向
       //                     */
       //                    Bitmap bitmap =
       // ImageTools.rotaingImageView(ImageTools.readPictureDegree(files.get(i)), cameraBitmap);
       //                    FileTools.createDirs("萌宝派");
       //                    File sendFile = new
       // File(Environment.getExternalStorageDirectory().getAbsoluteFile(), File.separator + "萌宝派"
       // + File.separator + new File(files.get(i)).getName());
       //
       //                    boolean b = ImageTools.saveBitmap(bitmap, sendFile.getAbsolutePath());
       // 图片处理
       //                    if (b) {
       multipartBuilder.addFormDataPart(
           "image" + i,
           "image" + i,
           RequestBody.create(MEDIA_TYPE_PNG, getSmallBitmap(files.get(i))));
       Log.i(TAG, "add picture addres = " + files.get(i) + "image" + (i + 1));
       //                    }
       //                }
     }
   }
   RequestBody formBody = multipartBuilder.build();
   Request request = new Request.Builder().url(url).post(formBody).build();
   enqueue(request, callback);
 }
  /**
   * 构造POST、PUT、DELETE请求对象
   *
   * @param pathUrl
   * @param params
   * @return
   */
  private Request buildRequest(String method, String pathUrl, Map<String, Object> params) {

    String fullUrl = this.baseUrl + pathUrl;
    RequestBody body = null;
    boolean hasFile = false;

    if (null != params) {

      Set<String> keys = params.keySet();
      for (String key : keys) {
        Object o = params.get(key);
        if (null == o) {
          continue;
        }
        if (o instanceof File) {
          hasFile = true;
          break;
        } else if (o instanceof List) {
          List list = (List) o;
          for (int i = 0; i < list.size(); i++) {
            Object o2 = list.get(i);
            if (null == o2) {
              continue;
            }
            if (o2 instanceof File || o2 instanceof byte[]) {
              hasFile = true;
              break;
            }
          }
        }
        if (hasFile) {
          break;
        }
      }
      if (hasFile) {
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        for (String key : keys) {
          Object o = params.get(key);
          if (null == o) {
            Timber.e("参数%s为NULL. ", key);
            continue;
          }

          if (o instanceof List) {
            List list = (List) o;
            for (int i = 0; i < list.size(); i++) {
              Object o2 = list.get(i);
              if (null == o2) {
                continue;
              }
              addPart(multipartBuilder, key, o2);
            }
          } else if (o instanceof Map) {
            Timber.e("don't support Map as parameter value. %s", o);
          } else {
            addPart(multipartBuilder, key, o);
          }
        }
        body = multipartBuilder.build();

      } else {

        FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
        for (String key : keys) {
          Object o = params.get(key);
          if (null == o) {
            Timber.e("参数%s为NULL. ", key);
            continue;
          }
          formEncodingBuilder.add(key, o.toString());
        }
        body = formEncodingBuilder.build();
      }
    } else {

      FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
      formEncodingBuilder.add("_utm_", System.currentTimeMillis() + "");
      body = formEncodingBuilder.build();
    }

    Request.Builder builder = new Request.Builder().url(fullUrl).method(method, body);
    wrapHttpHeader(builder, pathUrl);
    return builder.build();
  }