Exemplo n.º 1
0
  public static void sendMobileNumberToServer(Context context, String user_cell_number) {
    OkHttpClient okhttp = new OkHttpClient();
    String json =
        String.format(
            "{\"user_id\" : \"%s\",\"user_mobile_number\" : \"%s\"}",
            com.example.muditi.deligoo.Omoyo.shared.getString("user_id", "1007"), user_cell_number);
    final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    RequestBody requestbody = RequestBody.create(JSON, json);
    Request request =
        new Request.Builder()
            .url(
                "http://"
                    + context.getResources().getString(R.string.ip)
                    + "/userMobileNumberDataEntry/")
            .post(requestbody)
            .build();
    Call call = okhttp.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {}

          @Override
          public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
              String data = response.body().string();
              com.example.muditi.deligoo.Omoyo.edit.putBoolean(
                  "user_mobile_number_sended_to_server_successfully", true);
              com.example.muditi.deligoo.Omoyo.edit.commit();
            }
          }
        });
  }
Exemplo n.º 2
0
  /**
   * Uploads the image to the server
   *
   * @param b
   * @param listener
   */
  public void uploadImage(final Bitmap b, final OnResponseListener listener) {
    OkHttpClient httpClient = new OkHttpClient();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // encode image as PNG, re-encoding as JPG may cause compression artefacts to be visible
    b.compress(Bitmap.CompressFormat.PNG, 0, bos);

    RequestBody requestBody =
        new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                // the filename parameter is needed to specify that this is indeed a file and not an
                // inline
                // attachment
                Headers.of(
                    "Content-Disposition", "form-data; name=\"image\"; filename=\"image.png\""),
                RequestBody.create(MediaType.parse("image/png"), bos.toByteArray()))
            .build();
    Request request = new Request.Builder().url(UPLOAD_ENDPOINT).post(requestBody).build();

    Call call = httpClient.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {}

          @Override
          public void onResponse(Response response) throws IOException {
            listener.onResponse(new ServerResponse(response.code(), response.body().string()));
          }
        });
  }
Exemplo n.º 3
0
  public static void shoploader(final Context context) {
    OkHttpClient okhttp = new OkHttpClient();
    String json = String.format("{\"shop_id\" : \"%s\"}", Omoyo.currentShopId);
    final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    RequestBody requestbody = RequestBody.create(JSON, json);
    Request request =
        new Request.Builder()
            .url("http://" + context.getResources().getString(R.string.ip) + "/shop/")
            .post(requestbody)
            .build();
    Call call = okhttp.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {}

          @Override
          public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
              String data = response.body().string();
              com.example.muditi.deligoo.Omoyo.edit.putString("shop", data);
              com.example.muditi.deligoo.Omoyo.edit.commit();
            }
          }
        });
  }
Exemplo n.º 4
0
  @Override
  public void invokeAsyn(final ResultCallback callback) {
    prepareInvoked(callback);

    final Call call = mOkHttpClient.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {
            setErrorResId();
            mOkHttpClientManager.sendFailResultCallback(request, e, callback);
          }

          @Override
          public void onResponse(Response response) {
            InputStream is = null;
            try {
              is = response.body().byteStream();
              ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);
              ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(imageview);
              int inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);
              try {
                is.reset();
              } catch (IOException e) {
                response = getInputStream();
                is = response.body().byteStream();
              }

              BitmapFactory.Options ops = new BitmapFactory.Options();
              ops.inJustDecodeBounds = false;
              ops.inSampleSize = inSampleSize;
              final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
              mOkHttpClientManager
                  .getDelivery()
                  .post(
                      new Runnable() {
                        @Override
                        public void run() {
                          imageview.setImageBitmap(bm);
                        }
                      });
              mOkHttpClientManager.sendSuccessResultCallback(request, callback);
            } catch (Exception e) {
              setErrorResId();
              mOkHttpClientManager.sendFailResultCallback(request, e, callback);

            } finally {
              try {
                if (is != null) {
                  is.close();
                }
              } catch (IOException e) {
              }
            }
          }
        });
  }
Exemplo n.º 5
0
    /** 加载图片 */
    public void displayImage(final ImageView view, final String url, final int errorResId) {
      final Request request = new Request.Builder().url(url).build();
      Call call = mOkHttpClient.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
              setErrorResId(view, errorResId);
            }

            @Override
            public void onResponse(Response response) {
              InputStream is = null;
              try {
                is = response.body().byteStream();
                ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);
                ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(view);
                int inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);
                try {
                  is.reset();
                } catch (IOException e) {
                  response = mGetDelegate.get(url);
                  is = response.body().byteStream();
                }

                BitmapFactory.Options ops = new BitmapFactory.Options();
                ops.inJustDecodeBounds = false;
                ops.inSampleSize = inSampleSize;
                final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
                mDelivery.post(
                    new Runnable() {
                      @Override
                      public void run() {
                        view.setImageBitmap(bm);
                      }
                    });
              } catch (Exception e) {
                setErrorResId(view, errorResId);

              } finally {
                if (is != null)
                  try {
                    is.close();
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
              }
            }
          });
    }
  @Override
  public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    OkHttpClient client = okHttpClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder =
        new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();

    for (final String name : headers.keySet()) {
      okHttpRequestBuilder.addHeader(name, headers.get(name));
    }

    for (final String name : additionalHeaders.keySet()) {
      okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus =
        new BasicStatusLine(
            parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(),
            okHttpResponse.message());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();

    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
      final String name = responseHeaders.name(i), value = responseHeaders.value(i);

      if (name != null) {
        response.addHeader(new BasicHeader(name, value));
      }
    }

    return response;
  }
  private void call(
      Request request,
      final Net.Parser<T> parser,
      final Net.Callback<T> callback,
      final Object tag) {
    Request.Builder builder = request.newBuilder();
    if (tag != null) builder.tag(tag);
    // 在这里添加头部文件
    LinkedHashMap<String, String> map = headers();
    if (map != null && !map.isEmpty()) {
      for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
        String key = iterator.next();
        builder.addHeader(key, map.get(key));
      }
      request = builder.build();
    }

    OkHttpClient client = mClient.clone();
    client.setConnectTimeout(20, TimeUnit.SECONDS);

    final Call call = client.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, final IOException e) {
            final String msg = e.getMessage();
            mHandler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    onError(callback, msg);
                  }
                });
          }

          @Override
          public void onResponse(final Response response) throws IOException {
            final String resp = response.body().string();
            mHandler.post(
                new Runnable() {
                  @Override
                  public void run() {
                    onNetResponse(parser, callback, resp);
                  }
                });
          }
        });
  }
Exemplo n.º 8
0
    /**
     * 异步下载文件
     *
     * @param url
     * @param destFileDir 本地文件存储的文件夹
     * @param callback
     */
    public void downloadAsyn(
        final String url, final String destFileDir, final ResultCallback callback) {
      final Request request = new Request.Builder().url(url).build();
      final Call call = mOkHttpClient.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(final Request request, final IOException e) {
              sendFailedStringCallback(request, e, callback);
            }

            @Override
            public void onResponse(Response response) {
              InputStream is = null;
              byte[] buf = new byte[2048];
              int len = 0;
              FileOutputStream fos = null;
              try {
                is = response.body().byteStream();

                File dir = new File(destFileDir);
                if (!dir.exists()) {
                  dir.mkdirs();
                }
                File file = new File(dir, getFileName(url));
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                  fos.write(buf, 0, len);
                }
                fos.flush();
                // 如果下载文件成功,第一个参数为文件的绝对路径
                sendSuccessResultCallback(file.getAbsolutePath(), callback);
              } catch (IOException e) {
                sendFailedStringCallback(response.request(), e, callback);
              } finally {
                try {
                  if (is != null) is.close();
                } catch (IOException e) {
                }
                try {
                  if (fos != null) fos.close();
                } catch (IOException e) {
                }
              }
            }
          });
    }
Exemplo n.º 9
0
 /**
  * Execute HTTP call and deserialize the HTTP response body into the given return type.
  *
  * @param returnType The return type used to deserialize HTTP response body
  * @param <T> The return type corresponding to (same with) returnType
  * @param call Call
  * @return ApiResponse object containing response status, headers and data, which is a Java object
  *     deserialized from response body and would be null when returnType is null.
  * @throws ApiException If fail to execute the call
  */
 public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
   try {
     Response response = call.execute();
     T data = handleResponse(response, returnType);
     return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
   } catch (IOException e) {
     throw new ApiException(e);
   }
 }
  /**
   * 删除数据.
   *
   * @param url
   * @param params
   * @param apiCallback
   * @return Call
   */
  public Call asyncDelete(
      final String url, Map<String, Object> params, final APICallback apiCallback) {

    final Request request = buildRequest("DELETE", url, params);

    Call call = client.newCall(request);

    this.wifiLock.acquire();

    final ProtobufReponseCallBack responseCallback =
        new ProtobufReponseCallBack(
            appSession.get().getUserId(), url, apiCallback, request, this, call);
    // callBackList.add(responseCallback);

    call.enqueue(responseCallback);

    return call;
  }
Exemplo n.º 11
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String apiKey = "294fd84ca1cfe08b27b8de470fef717b";
    double latitude = 37.8267;
    double longitude = -122.423;
    String forecastUrl =
        "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;

    if (isNetworkAvailable()) {

      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder().url(forecastUrl).build();
      Call call = client.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {}

            @Override
            public void onResponse(Response response) throws IOException {
              try {
                Log.v(TAG, response.body().string());
                if (response.isSuccessful()) {

                } else {
                  alertUserAboutError();
                }
              } catch (IOException e) {
                Log.e(TAG, "Exception caught: ", e);
              }
            }
          });

    } else {
      Toast.makeText(MainActivity.this, R.string.network_unavailable, Toast.LENGTH_LONG).show();
    }

    Log.d(TAG, "Main UI code is running!");
  }
  /**
   * 异步读取URL, 返回Protobuf
   *
   * @param url
   * @param params
   * @return
   */
  public Call asyncGet(
      final String url, Map<String, Object> params, final APICallback apiCallback) {

    // RunningStatProvider.instance.printMemoryUsage("beforeAsyncGet");

    final Request request = buildGetRequest(url, params);

    Call call = client.newCall(request);

    this.wifiLock.acquire();

    final ProtobufReponseCallBack responseCallback =
        new ProtobufReponseCallBack(
            appSession.get().getUserId(), url, apiCallback, request, this, call);
    // callBackList.add(responseCallback);

    call.enqueue(responseCallback);

    return call;
  }
Exemplo n.º 13
0
  /**
   * Execute HTTP call asynchronously.
   *
   * @see #execute(Call, Type)
   * @param <T> Type
   * @param call The callback to be executed when the API call finishes
   * @param returnType Return type
   * @param callback ApiCallback
   */
  @SuppressWarnings("unchecked")
  public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {
            callback.onFailure(new ApiException(e), 0, null);
          }

          @Override
          public void onResponse(Response response) throws IOException {
            T result;
            try {
              result = (T) handleResponse(response, returnType);
            } catch (ApiException e) {
              callback.onFailure(e, response.code(), response.headers().toMultimap());
              return;
            }
            callback.onSuccess(result, response.code(), response.headers().toMultimap());
          }
        });
  }
Exemplo n.º 14
0
  private void getForecast(double latitude, double langitude) {

    adjustType();

    String apiKey = "abaa9b12255d3e6bc8d4140fafbdccec";

    String forecastUrl =
        "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + langitude;

    if (isNetworkAvailable()) {

      runOnUiThread(
          new Runnable() {
            @Override
            public void run() {
              toggleRefresh();
            }
          });
      //        implementing the request
      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder().url(forecastUrl).build();
      //          Asyncronous Implementation
      Call call = client.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });
              alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
              try {
                //            Response response = call.execute(); This does not work since it clogs
                // up the main thread, we need a asyncronous approach

                runOnUiThread(
                    new Runnable() {
                      @Override
                      public void run() {
                        toggleRefresh();
                      }
                    });

                if (response.isSuccessful()) {
                  String JsonResponse = response.body().string();
                  mForecast = parseForecastDetailes(JsonResponse);
                  runOnUiThread(
                      new Runnable() {
                        @Override
                        public void run() {
                          updateDisplay();
                        }
                      });

                } else alertUserAboutError();
              } catch (IOException e) {
                Log.e(TAG, "Exception caouth: ", e);
              } catch (JSONException e) {
                Log.e(TAG, "JSONException", e);
              }
            }
          });
    } else {
      Toast.makeText(this, getString(R.string.Network_unavailable), Toast.LENGTH_LONG).show();
    }
  }
  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(Request request, 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(request.urlString());
            callback.onFailure(new DebugServerException(sb.toString()));
          }

          @Override
          public void onResponse(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(request.urlString())
                    .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();
              }
            }
          }
        });
  }
Exemplo n.º 16
0
 public <T> T execute(Request request, Class<T> clazz) throws IOException {
   Call call = mOkHttpClient.newCall(request);
   Response execute = call.execute();
   String respStr = execute.body().string();
   return mGson.fromJson(respStr, clazz);
 }
Exemplo n.º 17
0
  public void clickAddCheckList(View view) {
    odoString = odoEditText.getText().toString().trim();
    deepString = deepEditText.getText().toString().trim();
    presureString = presureEditText.getText().toString().trim();
    // commentString = commentEditText.getText().toString().trim();
    int month = checkDatePicker.getMonth() + 1;
    dateString = checkDatePicker.getYear() + "-" + month + "-" + checkDatePicker.getDayOfMonth();

    reasonNameString = reason1Spinner.getSelectedItem().toString();
    reasonName2String = reason2Spinner.getSelectedItem().toString();

    if (reasonNameString.equals("--select reason--")) {

    } else {
      if (reasonNameString.equals(reasonName2String)
          || reasonName2String.equals(reasonNameString)) {
        reasonNameString = reasonNameString.toString();
        reasonName2String = "";
      } else {
        reasonNameString = reasonNameString.toString();
        reasonName2String = reasonName2String.toString();
      }
    }
    if (reasonName2String.equals("--select reason--")) {

    } else {
      if (reasonNameString.equals(reasonName2String)
          || reasonName2String.equals(reasonNameString)) {
        reasonNameString = reasonNameString.toString();
        reasonName2String = "";
      } else {
        reasonNameString = reasonNameString.toString();
        reasonName2String = reasonName2String.toString();
      }
    }

    // reasonIdString = reason1Spinner.get
    Log.d("Date", dateString);
    Log.d("Spinner", reasonNameString + " :: Spinner 2 ::" + reasonName2String);

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody =
        new FormEncodingBuilder()
            .add("isAdd", "true")
            .add("odo", odoString)
            .add("deepTread", deepString)
            .add("presure", presureString)
            .add("checkDate", dateString)
            .add("tire_id", tireIdString)
            .add("username", username)
            .add("reason1", reasonNameString)
            .add("reason2", reasonName2String)
            .build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(url).post(requestBody).build();

    Call call = okHttpClient.newCall(request);
    call.enqueue(
        new Callback() {
          @Override
          public void onFailure(Request request, IOException e) {
            Log.d("Call", "Failure");
          }

          @Override
          public void onResponse(Response response) throws IOException {
            Log.d("Call", "Success");
            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    Toast.makeText(
                            AddCheckListActivity.this,
                            "Add Checklist Successful!!",
                            Toast.LENGTH_SHORT)
                        .show();
                  }
                });

            finish();
          }
        });
  }
Exemplo n.º 18
0
  private void getForcast() {
    String latitude = String.valueOf(mCurrentLatitude);
    String longitude = String.valueOf(mCurrentLongitude);

    String APIKey = "b1dd6d714a50362e78bf8094dc562ec2";
    String forecastUrl =
        "https://api.forecast.io/forecast/" + APIKey + "/" + latitude + "," + longitude;

    if (isNetworkAvailable()) {
      toggleRefresh();

      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder().url(forecastUrl).build();

      Call call = client.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });
              alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });

              try {
                String jsonData = response.body().string();
                Log.v(TAG, response.body().string());
                if (response.isSuccessful()) {
                  mForecast = parseForecastDetails(jsonData);
                  runOnUiThread(
                      new Runnable() {
                        @Override
                        public void run() {
                          updateDisplay();
                        }
                      });
                } else {
                  alertUserAboutError();
                }
              } catch (IOException | JSONException e) {
                Log.e(TAG, "Exception caught ", e);
              }
            }
          });

    } else {
      Toast.makeText(this, R.string.network_error, Toast.LENGTH_LONG).show();
    }
  }
Exemplo n.º 19
0
 /**
  * 同步Get请求方法
  *
  * @param url
  * @return
  * @throws IOException
  */
 private Response p_getSync(String url) throws IOException {
   final Request request = new Request.Builder().url(url).build();
   Call call = client.newCall(request);
   Response response = call.execute();
   return response;
 }
Exemplo n.º 20
0
  // Metodo que consigue la informacion de la api de forecast
  private void getForecast() {
    String apiKey = "6bdeb587cb42fa93bc6d74b77c56cb21";
    double latitude = 8.983333; // 37.8267;
    double longitude = -79.516670; // -122.423;
    String forecastUrl =
        "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;

    // Se hace una condicion para ver si la red esta disponible
    if (ifNetworkAvailable()) {

      toggleRefresh(); // Da a la vista el progressbar y esconder la imagen de actualizar

      // Inicia la comunicacion
      OkHttpClient client = new OkHttpClient(); // Inicia el cliente
      Request request = new Request.Builder().url(forecastUrl).build(); // construye el pedido

      Call call = client.newCall(request); // La llamada
      // Comienza a buscar la informacion en un thread diferent(no el principal)
      call.enqueue(
          new Callback() {

            // Si falla la llamdda
            @Override
            public void onFailure(Request request, IOException e) {

              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });
              alertUserAboutError();
            }

            // La la respuesta se da
            @Override
            public void onResponse(Response response) throws IOException {

              /*Si la respuesta es correcta se llama al thread principal para que haga un
               * cambio en la interface(solamente se puede modificar la interface en el thread
               * principal de la aplicacion)  RUNONUITHREAD*/

              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });

              try {

                /*La respuesta que manda la pagina*/
                String jsonData = response.body().string();
                Log.v(TAG, jsonData);
                if (response.isSuccessful()) {
                  mForecast = parseForecast(jsonData);
                  runOnUiThread(
                      new Runnable() {
                        @Override
                        public void run() {
                          updateDisplay();
                        }
                      });

                } else {
                  alertUserAboutError();
                }
              } catch (IOException e) {
                Log.e(TAG, "Exception caught", e);
              } catch (JSONException e) {
                Log.e(TAG, "Exception caught", e);
              }
            }
          });
    } else {

      // Este codigo corre si no hay red
      NoNetWrokMessage();
    }
  }
Exemplo n.º 21
0
  private void calculateDistance(Context context, final String shop_id) {
    final JSONArray putArray = new JSONArray();

    try {
      JSONArray jsonArray =
          new JSONArray(
              com.example.muditi.deligoo.Omoyo.shared.getString("coordinateOfShop", "coordinate"));
      String latitude = null, longitude = null;
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        if (jsonObject.getString("shop_id").equals(shop_id)) {
          latitude = jsonObject.getString("shop_latitude");
          longitude = jsonObject.getString("shop_longitude");
        }
      }
      OkHttpClient okhttp = new OkHttpClient();
      StringBuilder builder =
          new StringBuilder("https://maps.googleapis.com/maps/api/distancematrix/json?");
      builder.append(
          "origins="
              + com.example.muditi.deligoo.Omoyo.shared.getString("latitude", "41.000")
              + ","
              + com.example.muditi.deligoo.Omoyo.shared.getString("longitude", "41.0"));
      builder.append("&");
      builder.append("destinations=" + latitude + "," + longitude);
      builder.append("&");
      builder.append("language=en");
      builder.append("&");
      builder.append("mode=driving");
      builder.append("&");
      builder.append("key=" + context.getString(R.string.app_key));
      Request request = new Request.Builder().url(builder.toString()).get().build();
      Call call = okhttp.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {}

            @Override
            public void onResponse(Response response) throws IOException {

              if (response.isSuccessful()) {
                final String data = response.body().string();
                try {
                  JSONObject putObject = new JSONObject();
                  JSONObject jsonObject1 = new JSONObject(data);
                  if (jsonObject1.getString("status").equals("OK"))
                    try {
                      putObject.put("shop_id", shop_id);
                      putObject.put(
                          "distance",
                          jsonObject1
                              .getJSONArray("rows")
                              .getJSONObject(0)
                              .getJSONArray("elements")
                              .getJSONObject(0)
                              .getString("value"));
                      JSONArray jsonArray1 =
                          new JSONArray(
                              com.example.muditi.deligoo.Omoyo.shared.getString("distance", ""));
                      jsonArray1.put(jsonArray1.length(), putObject);
                      com.example.muditi.deligoo.Omoyo.edit.putString(
                          "distance", jsonArray1.toString());
                      com.example.muditi.deligoo.Omoyo.edit.commit();
                    } catch (JSONException jx) {

                    }
                } catch (JSONException jj) {

                }
              }
            }
          });

    } catch (JSONException jx) {

    }
  }
Exemplo n.º 22
0
  private void getForecast(double latitude, double longitude) {
    String apiKey = "27974c4bc33201748eaf542a6769c3b7";

    String forecastUrl =
        "https://api.forecast.io/forecast/"
            + apiKey
            + "/"
            + latitude
            + ","
            + longitude
            + "?units=si";
    // let forecastUrl = NSURL(string: "37.8267,-122.423?units=si", relativeToURL: baseUrl)
    if (isNetworkAvailable()) {
      refresToggle();
      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder().url(forecastUrl).build();

      Call call = client.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      refresToggle();
                    }
                  });
              alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      refresToggle();
                    }
                  });
              try {
                String jsonData = response.body().string();
                Log.v(TAG, jsonData);
                if (response.isSuccessful()) {
                  mCurrentWeather = getCurrentDetails(jsonData);
                  runOnUiThread(
                      new Runnable() {
                        @Override
                        public void run() {
                          updateDisplay();
                        }
                      });
                } else {
                  alertUserAboutError();
                }
              } catch (IOException e) {
                Log.e(TAG, "Exception caught: ", e);
              } catch (JSONException e) {
                Log.e(TAG, "Exception caught: ", e);
              }
            }
          });
    } else {
      Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG)
          .show();
    }
  }
Exemplo n.º 23
0
 /** 同步的Get请求 */
 public Response get(String url) throws IOException {
   final Request request = new Request.Builder().url(url).build();
   Call call = mOkHttpClient.newCall(request);
   Response execute = call.execute();
   return execute;
 }
Exemplo n.º 24
0
 public Response execute() throws IOException {
   generateCall(null);
   return call.execute();
 }
Exemplo n.º 25
0
 public void cancel() {
   if (call != null) {
     call.cancel();
   }
 }
  /**
   * @param context Context
   * @param media Media data
   * @param languageCode Code of language
   * @param callback Network callback
   * @return Call
   */
  public static Call download(
      final Context context,
      final Media media,
      final String languageCode,
      final com.squareup.okhttp.Callback callback) {
    OkHttpClient client = ButterApplication.getHttpClient();
    if (media.subtitles != null && media.subtitles.containsKey(languageCode)) {
      try {
        Request request = new Request.Builder().url(media.subtitles.get(languageCode)).build();
        Call call = client.newCall(request);

        final File subsDirectory = getStorageLocation(context);
        final String fileName = media.videoId + "-" + languageCode;
        final File srtPath = new File(subsDirectory, fileName + ".srt");

        if (srtPath.exists()) {
          callback.onResponse(null);
          return call;
        }

        call.enqueue(
            new com.squareup.okhttp.Callback() {
              @Override
              public void onFailure(Request request, IOException e) {
                callback.onFailure(request, e);
              }

              @Override
              public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                  InputStream inputStream = null;
                  boolean failure = false;
                  try {

                    subsDirectory.mkdirs();
                    if (srtPath.exists()) {
                      File to = new File(subsDirectory, "temp" + System.currentTimeMillis());
                      srtPath.renameTo(to);
                      to.delete();
                    }

                    inputStream = response.body().byteStream();
                    String urlString = response.request().urlString();

                    if (urlString.contains(".zip") || urlString.contains(".gz")) {
                      SubsProvider.unpack(inputStream, srtPath, languageCode);
                    } else if (SubsProvider.isSubFormat(urlString)) {
                      parseFormatAndSave(urlString, srtPath, languageCode, inputStream);
                    } else {
                      callback.onFailure(
                          response.request(), new IOException("FatalParsingException"));
                      failure = true;
                    }
                  } catch (FatalParsingException e) {
                    e.printStackTrace();
                    callback.onFailure(
                        response.request(), new IOException("FatalParsingException"));
                    failure = true;
                  } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    callback.onFailure(response.request(), e);
                    failure = true;
                  } catch (IOException e) {
                    e.printStackTrace();
                    callback.onFailure(response.request(), e);
                    failure = true;
                  } finally {
                    if (inputStream != null) inputStream.close();

                    if (!failure) callback.onResponse(response);
                  }
                } else {
                  callback.onFailure(response.request(), new IOException("Unknown error"));
                }
              }
            });

        return call;
      } catch (RuntimeException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    callback.onFailure(null, new IOException("Wrong media"));
    return null;
  }
 public void cancelDownloadBundleFromURL() {
   if (mDownloadBundleFromURLCall != null) {
     mDownloadBundleFromURLCall.cancel();
     mDownloadBundleFromURLCall = null;
   }
 }
Exemplo n.º 28
0
  private void getForecast(double latitude, double longitude) {
    String apiKey =
        "dcee4386a92b30a378582ccd4091306d"; // Setting the input parts of the API URL into
    // parameters
    String forecastURL =
        "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;
    if (networkIsAvailable()) {
      toggleRefresh(); // This will make the ProgressBar VISIBLE
      OkHttpClient client = new OkHttpClient(); // Main CLIENT object
      Request request =
          new Request.Builder()
              .url(forecastURL)
              .build(); // This builds the request we're going to send to the server through
      // chaining - .url() supplies the url for .build() to actually build it
      // and Request.builder() specifies that we are building a request for the server
      Call call = client.newCall(request);
      call.enqueue(
          new Callback() { // .enqueue MAKES THIS AN ASYNCHRONOUS TASK! (Instead of .execute())

            @Override
            public void onFailure(Request request, IOException e) {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });
              alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh(); // Now, with the progress bar VISIBLE, when we get a
                      // response, we will now set it to INVISIBLE so we can
                      // refresh
                    }
                  });
              try {
                String weatherData =
                    response.body().string(); // Declaring our JSON data to use in many places
                Log.v(
                    TAG,
                    weatherData); // Logs a VERBOSE string that is the body of the response we get
                if (response.isSuccessful()) {
                  mForecast = parseForecastDetails(weatherData);
                  // Log.v was cut out b/c we want it to log regardless in the if and else statement

                  runOnUiThread(
                      new Runnable() { // Allows updateDisplay() to run and prepare code for main
                        // thread while not running on it
                        @Override
                        public void run() {
                          updateDisplay(); // Updates the values EVERY time you call for data
                        }
                      });
                } else {
                  alertUserAboutError(); // This alerts the user that data wasn't retrieved
                  // successfully
                }
              } catch (JSONException e) {
                Log.e(
                    TAG,
                    "Exception caught: ",
                    e); // Catches ALL our errors related to parsing JSON data -
                // EVERY METHOD THAT PARSES DATA SHOULD THROW A JSONEXCEPTION SO IT CAN BE CAUGHT
                // HERE
              }
            }
          });
    } else {
      alertUserAboutNetwork(); // Error sent if IF there was a network error
    }
  }
Exemplo n.º 29
0
  private void getForecast(double latitude, double longitude) {
    String apiKey = "32b0b275eea19d641b0069e91c91b50a";
    String forecastUrl =
        "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;

    if (isNetworkAvailable()) {
      toggleRefresh();
      OkHttpClient client = new OkHttpClient();
      Request request = new Request.Builder().url(forecastUrl).build();

      Call call = client.newCall(request);
      call.enqueue(
          new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });

              alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
              runOnUiThread(
                  new Runnable() {
                    @Override
                    public void run() {
                      toggleRefresh();
                    }
                  });

              try {
                String jsonData = response.body().string();
                if (response.isSuccessful()) {
                  mForecast = parseForecastDetails(jsonData);
                  runOnUiThread(
                      new Runnable() {
                        @Override
                        public void run() {
                          updateDisplay();
                        }
                      });
                } else {
                  alertUserAboutError();
                }
              } catch (IOException e) {
                Log.e(TAG, "Exception caught: ", e);
              } catch (JSONException e) {
                Log.e(TAG, "Exception caught: ", e);
              }
            }
          });
    } else {
      Toast.makeText(this, R.string.network_unavailable, Toast.LENGTH_LONG).show();
    }
  }
  /**
   * 下载文件
   *
   * @param url
   * @param cache
   * @param callback
   * @return
   */
  public Call asyncDownload(
      final String url, final boolean cache, final DownloadCallback callback) {

    final Request request = buildGetRequest(url, null);

    Call call = client.newCall(request);

    //        final ProgressResponseListener progressResponseListener = new
    // ProgressResponseListener() {
    //
    //            @Override
    //            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
    //                Timber.d("downloading... read=%s, total=%s", bytesRead, contentLength);
    //                callback.onDownloading(contentLength, bytesRead, done);
    //            }
    //        };
    //
    //        final Interceptor interceptor = new Interceptor() {
    //            @Override
    //            public Response intercept(Interceptor.Chain chain) throws IOException {
    //                //拦截
    //                Response originalResponse = chain.proceed(chain.request());
    //                //包装响应体并返回
    //                return originalResponse.newBuilder()
    //                        .body(new ProgressResponseBody(originalResponse.body(),
    // progressResponseListener))
    //                        .build();
    //            }
    //        };
    //
    //        //克隆
    //        OkHttpClient clone = client.clone();
    //
    //        //增加拦截器
    //        clone.networkInterceptors().add(interceptor);

    call.enqueue(
        new Callback() {

          @Override
          public void onFailure(Request request, IOException e) {
            Timber.e(e, "url : %s", url);
            callback.onError(e);
          }

          @Override
          public void onResponse(final Response response) throws IOException {

            if (!response.isSuccessful()) {

              Timber.e("ERROR url : %s, %s", url, response);
              callback.onError(new Exception(response.message()));

            } else {

              if (cache) {

                final String[] keys = new String[] {null};
                cacheProvider.put(
                    url,
                    new CacheWriter() {
                      @Override
                      public boolean write(String cacheKey, DiskLruCache.Editor editor) {

                        BufferedSink sink = null;
                        try {
                          OutputStream outputStream = editor.newOutputStream(0);
                          sink = Okio.buffer(Okio.sink(outputStream));
                        } catch (IOException e) {
                          Timber.e(e.getMessage(), e);
                          return false;
                        }

                        boolean hasError = false;

                        try {
                          sink.writeAll(response.body().source());
                          keys[0] = cacheKey;
                        } catch (IOException e) {
                          hasError = true;
                          Timber.e(e, e.getMessage());

                        } finally {
                          try {
                            sink.close();
                          } catch (IOException e) {
                            Timber.e(e, e.getMessage());
                          }
                          if (!hasError) {
                            Timber.d("Download Url: %s", request);
                          }
                        }

                        return !hasError;
                      }
                    });

                callback.onCompleted(keys[0], null);

              } else {

                callback.onCompleted(null, response.body());
              }
            }
          }
        });

    return call;
  }