예제 #1
0
  /**
   * 将Json转为Bean
   *
   * @param tag
   * @param url
   * @param headers
   * @param beanClass
   * @param getBeanCallBack
   * @param <T>
   */
  public static <T> void getBean(
      Object tag,
      String url,
      Map<String, String> headers,
      final Class<T> beanClass,
      final GetBeanCallBack<T> getBeanCallBack) {
    Logger.i(TAG, "getBean url:" + url);
    setCancel(false);
    if (mClient != null) {
      Request.Builder requestBuilder = new Request.Builder();
      requestBuilder.tag(tag);
      requestBuilder.url(url);
      appendHeaders(requestBuilder, headers);
      Request request = requestBuilder.build();
      mCall = mClient.newCall(request);
      mCalls.add(mCall);
      mCall.enqueue(
          new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              Logger.e(TAG, "getBean onFailure" + e.getMessage());
              EventBus.getDefault().post(new NetWorkBadEvent());
              getBeanCallBack.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
              if (response.isSuccessful()) {
                getBeanCallBack.onResponse(GsonUtils.fromJson(response.body().string(), beanClass));
              }
            }
          });
    }
  }
예제 #2
0
  /**
   * base 的 get请求
   *
   * @param tag
   * @param url
   * @param headers
   * @param getCallBack
   */
  public static void get(
      Object tag, String url, Map<String, String> headers, final GetCallBack getCallBack) {
    Logger.i(TAG, "get url :" + url);
    setCancel(false);
    if (mClient != null) {
      Request.Builder requestBuilder = new Request.Builder();
      requestBuilder.tag(tag);
      requestBuilder.url(url);
      appendHeaders(requestBuilder, headers);
      Request request = requestBuilder.build();
      mCall = mClient.newCall(request);
      mCalls.add(mCall);
      mCall.enqueue(
          new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              getCallBack.onFailure(call, e);
              Logger.e(TAG, "get onFailure:" + e.getMessage());
              EventBus.getDefault().post(new NetWorkBadEvent());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
              if (response.isSuccessful()) {
                getCallBack.onResponse(call, response);
              } else {
                getCallBack.onError(response.toString());
              }
            }
          });
    }
  }
예제 #3
0
  /**
   * post请求
   *
   * @param tag
   * @param url
   * @param headers
   * @param params
   * @param postCallBack
   */
  public static void post(
      Object tag,
      String url,
      Map<String, String> headers,
      Map<String, String> params,
      final PostCallBack postCallBack) {
    Logger.i(TAG, "post url :" + url);
    setCancel(false);
    RequestBody requestBody = null;
    FormBody.Builder formBodyBuilder = new FormBody.Builder();
    if (params == null || params.size() == 0) {
      requestBody = formBodyBuilder.build();
    } else {
      for (Map.Entry<String, String> me : params.entrySet()) {
        formBodyBuilder.add(me.getKey(), me.getValue());
      }
      requestBody = formBodyBuilder.build();
    }
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.tag(tag);
    requestBuilder.url(url);
    appendHeaders(requestBuilder, headers);
    requestBuilder.post(requestBody);
    Request request = requestBuilder.build();
    mCall = mClient.newCall(request);
    mCalls.add(mCall);
    mCall.enqueue(
        new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            Logger.e(TAG, "post onFailure :" + e.toString());
            postCallBack.onFailure(call, e);
            EventBus.getDefault().post(new NetWorkBadEvent());
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
              Logger.i(TAG, "post onResponse");
              postCallBack.onResponse(call, response);
            } else {
              Logger.i(TAG, "post onError: " + response.code());
              postCallBack.onError(response.code());
            }
          }
        });
  }
예제 #4
0
  /**
   * 文件上传
   *
   * @param tag
   * @param url
   * @param filePath
   * @param headers
   * @param params
   * @param uploadFileCallBack
   */
  public static void uploadFile(
      Object tag,
      String url,
      String filePath,
      Map<String, String> headers,
      Map<String, String> params,
      final UploadFileCallBack uploadFileCallBack) {
    Logger.i(TAG, "uploadFile url :" + url);
    setCancel(false);
    File file = new File(filePath);
    MultipartBody.Builder multipartBuilder =
        new MultipartBody.Builder().setType(MultipartBody.FORM);
    addParams(multipartBuilder, params);
    addFiles(multipartBuilder, new Pair<String, File>("file", file));
    progerssRequestBody = new ProgressRequestBody(multipartBuilder.build(), uploadFileCallBack);
    Request.Builder builder = new Request.Builder();
    appendHeaders(builder, headers);
    Request request = builder.tag(tag).url(url).post(progerssRequestBody).build();

    mCall = mClient.newCall(request);
    mCalls.add(mCall);
    mCall.enqueue(
        new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            Logger.e(TAG, "uploadFile onFailure :" + e.toString());
            uploadFileCallBack.onFailure(call, e);
            EventBus.getDefault().post(new NetWorkBadEvent());
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
              Logger.i(TAG, "uploadFile onResponse");
              uploadFileCallBack.onResponse(call, response);
            } else {
              Logger.i(TAG, "uploadFile onError: " + response.code());
              uploadFileCallBack.onError(response.code());
            }
          }
        });
  }
예제 #5
0
  /**
   * post提交Json
   *
   * @param tag
   * @param url
   * @param headers
   * @param json
   * @param postCallBack
   */
  public static void postJson(
      Object tag,
      String url,
      Map<String, String> headers,
      String json,
      final PostCallBack postCallBack) {
    Logger.i(TAG, "postJson url :" + url);
    setCancel(false);
    RequestBody postBody =
        RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.tag(tag);
    requestBuilder.url(url);
    appendHeaders(requestBuilder, headers);
    requestBuilder.post(postBody);
    Request request = requestBuilder.build();
    mCall = mClient.newCall(request);
    mCalls.add(mCall);
    mCall.enqueue(
        new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            Logger.e(TAG, "postJson onFailure :" + e.toString());
            postCallBack.onFailure(call, e);
            EventBus.getDefault().post(new NetWorkBadEvent());
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
              Logger.i(TAG, "postJson onResponse");
              postCallBack.onResponse(call, response);
            } else {
              Logger.i(TAG, "postJson onError: " + response.code());
              postCallBack.onError(response.code());
            }
          }
        });
  }
  public void downloadBundleFromURL(
      final BundleDownloadCallback callback, final String jsModulePath, final File outputFile) {
    final String bundleURL =
        createBundleURL(
            getDebugServerHost(), jsModulePath, getDevMode(), getHMR(), getJSMinifyMode());
    final Request request = new Request.Builder().url(bundleURL).build();
    mDownloadBundleFromURLCall = Assertions.assertNotNull(mClient.newCall(request));
    mDownloadBundleFromURLCall.enqueue(
        new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            // ignore callback if call was cancelled
            if (mDownloadBundleFromURLCall == null || mDownloadBundleFromURLCall.isCanceled()) {
              mDownloadBundleFromURLCall = null;
              return;
            }
            mDownloadBundleFromURLCall = null;

            StringBuilder sb = new StringBuilder();
            sb.append("Could not connect to development server.\n\n")
                .append("Try the following to fix the issue:\n")
                .append("\u2022 Ensure that the packager server is running\n")
                .append(
                    "\u2022 Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices\n")
                .append(
                    "\u2022 If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device\n")
                .append(
                    "\u2022 If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081\n\n")
                .append("URL: ")
                .append(call.request().url().toString());
            callback.onFailure(new DebugServerException(sb.toString()));
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
            // ignore callback if call was cancelled
            if (mDownloadBundleFromURLCall == null || mDownloadBundleFromURLCall.isCanceled()) {
              mDownloadBundleFromURLCall = null;
              return;
            }
            mDownloadBundleFromURLCall = null;

            // Check for server errors. If the server error has the expected form, fail with more
            // info.
            if (!response.isSuccessful()) {
              String body = response.body().string();
              DebugServerException debugServerException = DebugServerException.parse(body);
              if (debugServerException != null) {
                callback.onFailure(debugServerException);
              } else {
                StringBuilder sb = new StringBuilder();
                sb.append("The development server returned response error code: ")
                    .append(response.code())
                    .append("\n\n")
                    .append("URL: ")
                    .append(call.request().url().toString())
                    .append("\n\n")
                    .append("Body:\n")
                    .append(body);
                callback.onFailure(new DebugServerException(sb.toString()));
              }
              return;
            }

            Sink output = null;
            try {
              output = Okio.sink(outputFile);
              Okio.buffer(response.body().source()).readAll(output);
              callback.onSuccess();
            } finally {
              if (output != null) {
                output.close();
              }
            }
          }
        });
  }
예제 #7
0
  /**
   * 下载
   *
   * @param tag
   * @param url
   * @param targetPath
   * @param fileName
   * @param avaiable
   * @param downLoadCallBack
   */
  public static void downLoad(
      Object tag,
      final String url,
      final String targetPath,
      final String fileName,
      final long avaiable,
      final DownLoadCallBack downLoadCallBack) {
    Logger.i(TAG, "downLoad url:" + url);
    setCancel(false);
    if (TextUtils.isEmpty(url)) throw new NullPointerException("url can't be null");
    if (TextUtils.isEmpty(targetPath)) throw new NullPointerException("targetPath can't be null");
    if (mClient != null) {
      Logger.i(TAG, "-----");
      final Request request = new Request.Builder().tag(tag).url(url).build();
      mCall = mClient.newCall(request);
      mCalls.add(mCall);
      Logger.i(TAG, "-----url=" + url + ",targetPath=" + targetPath + ",fileName=" + fileName);
      mCall.enqueue(
          new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              Logger.e(TAG, "downLoad onFailure:" + e.getMessage());
              downLoadCallBack.onFailure(call, e);
              EventBus.getDefault().post(new NetWorkBadEvent());
            }

            @Override
            public void onResponse(Call call, Response response) {
              Logger.i(TAG, "-----response.isSuccessful()=" + response.isSuccessful());
              if (response.isSuccessful()) {
                File targetFile = new File(targetPath);
                if (!targetFile.exists()) {
                  targetFile.mkdirs();
                }
                Logger.i(TAG, "-----targetFile=" + targetFile);
                long total = response.body().contentLength();
                int current = 0;
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                // 判断内存卡剩余内存的大小
                if (avaiable > total) {
                  try {
                    Logger.i(TAG, "downLoad onStart total:" + total);
                    downLoadCallBack.onStart(total);

                    InputStream is = response.body().byteStream();
                    bis = new BufferedInputStream(is);
                    FileOutputStream fos =
                        new FileOutputStream(targetFile.getAbsolutePath() + "/" + fileName);
                    Logger.i(TAG, "文件存储:" + targetFile.getAbsolutePath() + "/" + fileName);
                    bos = new BufferedOutputStream(fos);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while (!isCancel && ((len = bis.read(buffer)) != -1)) {
                      current += len;
                      Logger.i(TAG, "downLoad onLoading current:" + current);
                      bos.write(buffer, 0, len);
                      downLoadCallBack.onLoading(current, total);
                    }
                    if (current < total) {
                      Logger.i(TAG, "downLoad onCancel");
                      downLoadCallBack.onCancel();
                    }
                  } catch (IOException e) {
                    Logger.e(TAG, "读写流出错:" + e.getMessage());
                    downLoadCallBack.onError(e);
                  } finally {
                    try {
                      if (bos != null) {
                        bos.close();
                        bos = null;
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                      downLoadCallBack.onError(e);
                    }
                    try {
                      if (bis != null) {
                        bis.close();
                        bis = null;
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                      downLoadCallBack.onError(e);
                    }
                    if (current == total) {
                      Logger.i(TAG, "downLoad onSucceed" + "文件保存在" + targetPath + "/" + fileName);
                      downLoadCallBack.onSucceed();
                    }
                  }
                } else {
                  Logger.i(TAG, "downLoad onSdCardLackMemory");
                  downLoadCallBack.onSdCardLackMemory(total, avaiable);
                }
              }
            }
          });
    }
  }