public static void getBooks(final String url, final CallBack callBack) {
    List<Book> list = null;
    if (TextUtils.isEmpty(url)) {
      callBack.callback(list);
    }

    AsyncHttpClient client = new AsyncHttpClient();
    client.get(
        url,
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            List<Book> list = parseBooks(response);
            if (callBack != null) {
              callBack.callback(list);
            }
          }

          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {}

          @Override
          public void onFailure(
              int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
          }
        });
  }
  public void makeVoipCall(final String number) {
    AudioManagerUtils.setLoudSpeaker(false);
    ((BaseActivity) getActivity()).showProgressDialog("Connecting VOIP Call");
    RequestParams params = new RequestParams();
    params.put("smartPagerID", SmartPagerApplication.getInstance().getPreferences().getUserID());
    params.put("uberPassword", SmartPagerApplication.getInstance().getPreferences().getPassword());

    AsyncHttpClient httpClient = new AsyncHttpClient();
    httpClient.post(
        getActivity().getApplicationContext(),
        Constants.BASE_REST_URL + "/getTwilioClientToken",
        params,
        new JsonHttpResponseHandler() {

          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            System.out.println("successful response: " + response);
            ((BaseActivity) getActivity()).hideProgressDialog();

            VoipPhone voipPhone =
                new VoipPhone(
                    ((BaseActivity) getActivity()).getApplicationContext(),
                    response.optString("token"));
            voipPhone.connect(number);
          }

          @Override
          public void onFailure(
              int statusCode, Header[] headers, String responseBody, Throwable error) {
            System.out.println("failure response: " + responseBody);
            ((BaseActivity) getActivity()).hideProgressDialog();
          }
        });
  }
示例#3
0
  private searchMenuMgr() {

    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
      socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      client = new AsyncHttpClient();
      client.setSSLSocketFactory(socketFactory);
      client.setCookieStore(new PersistentCookieStore(Login_Main.getContext()));
      client.setTimeout(10000);
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    }
  }
  private void asynCallToGoogleApi(String strQuery) {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    // https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=barack&obama&userip=INSERT-USER-IP
    String apiUrlCall = String.format(GOOGLE_API_URL, start, Uri.encode(strQuery));
    start += 8;
    apiUrlCall = addQueryParams(apiUrlCall);
    Log.d("DEBUG", apiUrlCall.toString());
    asyncHttpClient.get(
        apiUrlCall,
        new JsonHttpResponseHandler() {

          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            JSONArray jsonImageResults = null;
            try {
              jsonImageResults = response.getJSONObject("responseData").getJSONArray("results");

              imageResults.addAll(ImageResult.fromJsonArray(jsonImageResults));
              imageResultArrayAdapter.notifyDataSetChanged();
              Log.d("DEBUG", imageResults.toString());
            } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Log.i("Javier", "Finis2h");

    persistentCookieStore = new PersistentCookieStore(this);

    httpClient = new AsyncHttpClient();

    persistentCookieStore.clear();
    httpClient.setUserAgent(getUserAgent());
    httpClient.setCookieStore(persistentCookieStore);
    // httpClient.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
    // true);
    // httpClient.getHttpClient().getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,
    // true);

    // PROXY SETTING HERE FOR FIDDLER
    // HttpHost proxy = new HttpHost("192.168.150.82", 8888);
    // httpClient.getHttpClient().getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
    // proxy);
    //
    // printCookies();

    getSupportActionBar().setTitle("metro");

    editText1 = (EditText) findViewById(R.id.editText1);
    editText2 = (EditText) findViewById(R.id.editText2);
    editText3 = (EditText) findViewById(R.id.editText4);
    accountDetails = (TextView) findViewById(R.id.textView1);
    securityCharacters = (TextView) findViewById(R.id.textView2);
  }
  /**
   * Performs a POST request to the Singly API.
   *
   * <p>All network communication is performed in a separate thread. As such it is fine to call this
   * method from the main UI thread.
   *
   * <p>The AsyncApiResponseHandler parameter is an asynchronous callback handler that is used to
   * retrieve the result of the network request to the API. On success the response from the API is
   * returned. On failure a Throwable error object will be returned.
   *
   * <p>If an API call requires an access token it must be added to the queryParams passed into the
   * method.
   *
   * @param context The current android context.
   * @param apiEndpoint The Singly API endpoint to call.
   * @param queryParams Any query parameters to send along with the request.
   * @param responseHandler An asynchronous callback handler for the request.
   * @see https://singly.com/docs/api For documentation on Singly api calls.
   * @see SinglyUtils#getAccessToken(Context)
   */
  public void doPostApiRequest(
      Context context,
      String apiEndpoint,
      Map<String, String> queryParams,
      final AsyncApiResponseHandler responseHandler) {

    // get the http client and add api url
    AsyncHttpClient client = new AsyncHttpClient();
    Map<String, String> params = new LinkedHashMap<String, String>();
    if (queryParams != null) {
      params.putAll(queryParams);
    }
    String postApiCallUrl = SinglyUtils.createSinglyURL(apiEndpoint);
    RequestParams rparms = params.isEmpty() ? null : new RequestParams(params);

    // do an async post request
    client.post(
        postApiCallUrl,
        rparms,
        new AsyncHttpResponseHandler() {

          @Override
          public void onSuccess(String response) {
            responseHandler.onSuccess(response);
          }

          @Override
          public void onFailure(Throwable error) {
            responseHandler.onFailure(error);
          }
        });
  }
示例#7
0
 static {
   // // 使用默认的 cacheThreadPool
   client.setTimeout(150000);
   client.setConnectTimeout(150000);
   client.setMaxConnections(20);
   client.setResponseTimeout(200000);
 }
  private void queryMovie(String SearchString) {
    String strURL = "";
    try {
      strURL = URLEncoder.encode(SearchString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      Toast.makeText(this, "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    asyncHttpClient.get(
        QUERY_URL + strURL,
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(JSONObject jsonObject) {
            MovieSearchActivity.jsonObject = jsonObject;
            mDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Success !", Toast.LENGTH_LONG).show();
            Log.d("BMF Finder", jsonObject.toString());
            updateData(jsonObject);
          }

          @Override
          public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
            mDialog.dismiss();
            Toast.makeText(
                    getApplicationContext(),
                    "Error : " + statusCode + " " + throwable.getMessage(),
                    Toast.LENGTH_LONG)
                .show();
            Log.e("BMFinder", statusCode + " " + throwable.getMessage());
          }
        });
  }
  private void populateData() {
    // String query = etQuery.getText().toString();
    String searchUrl =
        "https://ajax.googleapis.com/ajax/services/search/images?q="
            + query
            + "&v=1.0&rsz=8&start="
            + imageNumber;
    searchUrl += setUrlWithImageSettings();
    Log.d("DEBUG", "SEARCH IRL IS " + searchUrl);
    imageNumber += 8;
    // Toast.makeText(this, "Searching for \""+query+"\"", Toast.LENGTH_SHORT).show();
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(
        searchUrl,
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            Log.d("DEBUG", response.toString());
            JSONArray imageResultsJSON = null;
            try {
              imageResultsJSON = response.getJSONObject("responseData").getJSONArray("results");
              aImageResults.addAll(ImageResult.fromJSONArray(imageResultsJSON));

            } catch (JSONException e) {
              e.printStackTrace();
            }
            Log.d("imageArray", imageResults.toString());
          }
        });
  }
示例#10
0
  private void getFriend() {
    AsyncHttpClient myClient;

    myClient = new AsyncHttpClient();
    myClient.setTimeout(SingleToneData.getInstance().getTimeOutValue());
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    myClient.setCookieStore(myCookieStore);

    String url = context.getString(R.string.url_gift_list);

    RequestParams params = new RequestParams();
    LoginUtils loginUtils = new LoginUtils(context);

    params.put("id", loginUtils.getId());
    params.put("pw", loginUtils.getPw());

    myClient.post(
        url,
        params,
        new AsyncHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            Log.i("(friend fragment)", new String(responseBody));
            getGiftFinish(new String(responseBody));
          }

          @Override
          public void onFailure(
              int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Toast.makeText(
                    context, getResources().getString(R.string.on_failure), Toast.LENGTH_SHORT)
                .show();
          }
        });
  }
  public MyRestClient(Context context) {
    this.client = new AsyncHttpClient();
    myCookieStore = new PersistentCookieStore(context);
    client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    client.setCookieStore(myCookieStore);
  }
  /**
   * Performs a POST request to the Singly API that allows specifying the body content of the
   * request. This is used when you need to POST raw content, such as text or images, to the API.
   *
   * <p>Any query parameters passed are appended to the URL versus being passed in the body of the
   * POST request.
   *
   * <p>All network communication is performed in a separate thread. As such it is fine to call this
   * method from the main UI thread.
   *
   * <p>The AsyncApiResponseHandler parameter is an asynchronous callback handler that is used to
   * retrieve the result of the network request to the API. On success the response from the API is
   * returned. On failure a Throwable error object will be returned.
   *
   * <p>If an API call requires an access token it must be added to the queryParams passed into the
   * method.
   *
   * @param context The current android context.
   * @param apiEndpoint The Singly API endpoint to call.
   * @param queryParams Any query parameters to send along with the request.
   * @param body The content to use as the body of the request.
   * @param contentType The MIME content type being sent.
   * @param responseHandler An asynchronous callback handler for the request.
   * @see https://singly.com/docs/api For documentation on Singly api calls.
   * @see SinglyUtils#getAccessToken(Context)
   */
  public void doBodyApiRequest(
      Context context,
      String apiEndpoint,
      Map<String, String> queryParams,
      byte[] body,
      String contentType,
      final AsyncApiResponseHandler responseHandler) {

    // get the http client and add api url
    AsyncHttpClient client = new AsyncHttpClient();
    Map<String, String> params = new LinkedHashMap<String, String>();
    if (queryParams != null) {
      params.putAll(queryParams);
    }
    String postApiCallUrl = SinglyUtils.createSinglyURL(apiEndpoint, params);

    // do an async post request with the raw body content
    client.post(
        context,
        postApiCallUrl,
        new ByteArrayEntity(body),
        contentType,
        new AsyncHttpResponseHandler() {

          @Override
          public void onSuccess(String response) {
            responseHandler.onSuccess(response);
          }

          @Override
          public void onFailure(Throwable error) {
            responseHandler.onFailure(error);
          }
        });
  }
  public void invokeWS(StringEntity entity) {
    AsyncHttpClient client = new AsyncHttpClient();
    client.post(
        getApplicationContext(),
        "http://mudgea3.cloudapp.net:5000/api/audio/1",
        entity,
        "application/json",
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
              Log.v("status is", response.toString());

            } catch (Exception e) {
              Log.e("JSON error", "errror");
            }
          }

          @Override
          public void onFailure(
              int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            Log.e("REST CALL ERROR", "tried to send audio " + statusCode);
            Log.e("audio error", errorResponse.toString());
          }
        });
  }
 @Override
 protected byte[] getResponseData(HttpEntity entity) throws IOException {
   if (entity != null) {
     InputStream instream = entity.getContent();
     long contentLength = entity.getContentLength();
     FileOutputStream buffer = new FileOutputStream(getTargetFile(), this.append);
     if (instream != null) {
       try {
         byte[] tmp = new byte[BUFFER_SIZE];
         int l, count = 0;
         // do not send messages if request has been cancelled
         while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
           count += l;
           buffer.write(tmp, 0, l);
           sendProgressMessage(count, contentLength);
         }
       } finally {
         AsyncHttpClient.silentCloseInputStream(instream);
         buffer.flush();
         AsyncHttpClient.silentCloseOutputStream(buffer);
       }
     }
   }
   return null;
 }
  @Override
  public void onColorChanged(int color) {
    picker.setOldCenterColor(picker.getColor());
    picker2.setOldCenterColor(picker2.getColor());
    refreshBackgroundColors();

    if (!requestPending) {
      requestPending = true;
      AsyncHttpClient client = new AsyncHttpClient();
      client.get(
          SettingsFragment.ip
              + "color?color&"
              + colorToString(Color.red(picker.getColor()) * getAlpha(picker.getColor()))
              + "&"
              + colorToString(Color.green(picker.getColor()) * getAlpha(picker.getColor()))
              + "&"
              + colorToString(Color.blue(picker.getColor()) * getAlpha(picker.getColor()))
              + "&"
              + colorToString(Color.red(picker2.getColor()) * getAlpha(picker2.getColor()))
              + "&"
              + colorToString(Color.green(picker2.getColor()) * getAlpha(picker2.getColor()))
              + "&"
              + colorToString(Color.blue(picker2.getColor()) * getAlpha(picker2.getColor()))
              + "",
          new AsyncHttpResponseHandler() {
            @Override
            public void onFinish() {
              requestPending = false;
            }
          });
    }
  }
  public void fetchPopularPhotos() {
    String url = "https://api.instagram.com/v1/media/popular?client_id=" + CLIENT_ID;

    // create a network client
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(
        url,
        null,
        new JsonHttpResponseHandler() {
          // on success
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // expecting a JSON object

            // iterate each item and decode the item into a java object

            JSONArray photosJSON = null;
            try {
              photosJSON = response.getJSONArray("data");
              // iterate
              for (int i = 0; i < photosJSON.length(); i++) {
                // get the JSON obj
                JSONObject photoJSON = photosJSON.getJSONObject(i);
                // decode the attributes of the json into a data model
                InstagramPhoto photo = new InstagramPhoto();
                photo.username = photoJSON.getJSONObject("user").getString("username");
                photo.caption = photoJSON.getJSONObject("caption").getString("text");
                photo.imageUrl =
                    photoJSON
                        .getJSONObject("images")
                        .getJSONObject("standard_resolution")
                        .getString("url");
                photo.profileImageUrl =
                    photoJSON.getJSONObject("user").getString("profile_picture");
                photo.imageHeight =
                    photoJSON
                        .getJSONObject("images")
                        .getJSONObject("standard_resolution")
                        .getInt("height");
                photo.likesCount = photoJSON.getJSONObject("likes").getInt("count");
                photo.createdTime = photoJSON.getLong("created_time");
                photo.type = photoJSON.getString("type");
                photo.comments = photoJSON.getJSONObject("comments").getJSONArray("data");
                photos.add(photo);
              }
            } catch (JSONException e) {
              e.printStackTrace();
            }
            aPhotos.notifyDataSetChanged();
            swipeContainer.setRefreshing(false);
          }

          @Override
          public void onFailure(
              int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
          }
        });
  }
 /** 更改photo名字 */
 private void changelnfo() {
   AsyncHttpClient client = new AsyncHttpClient();
   RequestParams params = new RequestParams();
   params.put("Photo", photo);
   params.put("act", "updateinfo");
   params.put("ID", NApplication.userid);
   client.post(Url.userLogin, params, change_info_handler);
 }
示例#18
0
 public static void setClient(AsyncHttpClient as) {
   client = as;
   client.addHeader("Accept-Language", Locale.getDefault().toString());
   client.addHeader("Host", HOST);
   client.addHeader("Connection", "Keep-Alive");
   client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
   setUserAgent(ApiClientHelper.getUserAgent(AppContext.getInstance()));
 }
  public void getDBSize() {
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put(Settings.DB_HOST, sharedPrefs.getValueStr(SharedPrefs.KEY_DB_HOST));
    params.put(Settings.DB_NAME, sharedPrefs.getValueStr(SharedPrefs.KEY_DB_NAME));
    params.put(Settings.DB_USER, sharedPrefs.getValueStr(SharedPrefs.KEY_DB_USERNAME));
    params.put(Settings.DB_PASSWORD, sharedPrefs.getValueStr(SharedPrefs.KEY_DB_PASSWORD));

    System.out.println("params: " + params.toString());

    String url = sharedPrefs.getValueStr(SharedPrefs.KEY_DOMAIN_NAME) + "/php/checkDBSize.php";
    Log.i("getDBSize", "URL: " + url);

    client.post(
        url,
        params,
        new AsyncHttpResponseHandler() {
          @Override
          public void onSuccess(String response) {
            System.out.println("sucess sa dbcheck");
            try {
              JSONObject json_data = new JSONObject(response);
              double size = (json_data.getDouble("size"));
              dataHandler.setDbSize(size);
              Log.i("checkDBSize", "DB Size: " + dataHandler.getDbSize());
              dialog.dismiss();
              updateDialog.dismiss();

              Intent intent = new Intent(getApplicationContext(), UpdateManager.class);
              startActivity(intent);

            } catch (Exception e) {
              updateDialog.dismiss();
              Log.e("Fail 3", e.toString());
            }
          }

          @Override
          public void onFailure(int statusCode, Throwable error, String content) {
            dialog.dismiss();
            System.out.println("failed sa dbcheck");
            if (statusCode == 404) {
              Log.e("getDBSize", "ERROR 404");
            } else if (statusCode == 500) {
              Log.e("getDBSize", "ERROR 500");
            } else {
              Log.e(
                  "getDBSize",
                  "ERROR OCCURED!  content: "
                      + content
                      + "\nstatus: "
                      + statusCode
                      + "\nerror: "
                      + error.toString());
            }
          }
        });
  }
示例#20
0
  /** public void run */
  public void run() {
    while (!Thread.currentThread().isInterrupted()) {

      // System.out.println(String.format("sentiment thread: (%d, %d)", this.m_inQueue.size(),
      // this.m_outQueue.size()));

      try {
        final Tweet t = m_inQueue.take();

        // build the url
        String urlString =
            "http://www.sentiment140.com/api/classify?text="
                + URLEncoder.encode(t.text)
                + "&query="
                + URLEncoder.encode(t.keyword);

        // send off the request
        AsyncHttpClient client = new AsyncHttpClient();

        client.get(
            urlString,
            new AsyncHttpResponseHandler() {

              @Override
              public void onSuccess(String response) {
                // parse the sentiment from response
                t.sentiment = Integer.parseInt((response.split("\"polarity\":")[1]).split(",")[0]);
                t.sentiment = (t.sentiment / 2) - 1;

                m_outQueue.offer(t);
              }

              @Override
              public void onFailure(Throwable thrwbl, String string) {
                System.out.println("sentiment request failed...");
                long currentTime = System.currentTimeMillis();
                // only show one per minute
                if (currentTime > m_LastWarningTime + 60000) {
                  m_webToasts.offer(
                      new WebToast(
                          "warning",
                          "We're having some trouble talking to the sentiment server. We'll keep trying, but you might want to check your internet connection.",
                          "Warning",
                          0,
                          0,
                          0));
                  m_LastWarningTime = currentTime;
                }
              }
            });

      } catch (InterruptedException ex) {
        // immediately reset interrupt flag
        Thread.currentThread().interrupt();
      }
    }
  }
 /** 登录,获取用户信息 */
 private void userlnfo() {
   AsyncHttpClient client = new AsyncHttpClient();
   RequestParams params = new RequestParams();
   params.put("act", "login");
   params.put("phone", phone);
   params.put("pass", pass);
   params.put("equipment", NApplication.device_token);
   client.post(Url.userLogin, params, user_info_handler);
 }
示例#22
0
  private void saveJSONToDatabse() {

    AsyncHttpClient cliente = new AsyncHttpClient();

    cliente.get(
        URLPOSTS,
        new JsonHttpResponseHandler() {
          @Override
          public void onSuccess(int statusCode, Header[] headers, JSONArray response) {

            for (int i = 0; i < response.length(); i++) {
              try {
                JSONObject jsonobject = response.getJSONObject(i);

                ContentValues contentValues = new ContentValues();
                contentValues.put(JobDbData._ID, jsonobject.getInt("id"));
                contentValues.put(JobDbData.COLUMN_TITLE, jsonobject.getString("title"));
                contentValues.put(
                    JobDbData.COLUMN_DESCRIPTION, jsonobject.getString("description"));
                contentValues.put(
                    JobDbData.COLUMN_POSTED_DATE, jsonobject.getString("posted_date"));

                getContentResolver().insert(JobDbData.CONTENT_URI, contentValues);

                JSONArray jsonArray = jsonobject.getJSONArray("contacts");
                for (int k = 0; k < jsonArray.length(); k++) {
                  String numerocontact = jsonArray.getString(k);
                  ContentValues contentValues2 = new ContentValues();
                  contentValues2.put(ContactDbData.COLUMN_JOB_ID, jsonobject.getInt("id"));
                  contentValues2.put(ContactDbData.COLUMN_NUMBER, numerocontact);

                  getContentResolver().insert(ContactDbData.CONTENT_URI, contentValues2);
                  ;
                }

              } catch (JSONException e) {
                e.printStackTrace();
              }
            }
            progressDialog.dismiss();
            fillListViewFromDB();
          }

          @Override
          public void onFailure(
              int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
            //                Log.d("onFailure", "onFailure", throwable);
            Log.i("Error !", "Ocurrio un error al conectarse al servidor!");
            //                Toast.makeText(ListadoActivity.class,"")
            AlertDialog.Builder builder = new AlertDialog.Builder(ListadoActivity.this);
            builder
                .setTitle("Error !")
                .setMessage("Ocurrio un error al conectarse al servidor!")
                .show();
          }
        });
  }
  public void invokeWS(RequestParams params, String lienWebService, final String lienJavascript) {
    // Show Progress Dialog
    prgDialog.show();
    // Make RESTful webservice call using AsyncHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    RequestHandle requestHandle =
        client.get(
            lienWebService,
            params,
            new AsyncHttpResponseHandler() {
              // When the response returned by REST has Http response code '200'
              @Override
              public void onSuccess(String response) {

                // Hide Progress Dialog
                prgDialog.hide();
                jsonResponse = response;

                webView = (WebView) findViewById(R.id.web);
                webView.addJavascriptInterface(new WebAppInterface(), "Android");
                webView.getSettings().setJavaScriptEnabled(true);
                webView.loadUrl(lienJavascript);
              }

              // When the response returned by REST has Http response code other than '200'
              @Override
              public void onFailure(int statusCode, Throwable error, String content) {
                // Hide Progress Dialog
                prgDialog.hide();
                // When Http response code is '404'
                if (statusCode == 404) {
                  Toast.makeText(
                          getApplicationContext(),
                          "Requested resource not found",
                          Toast.LENGTH_LONG)
                      .show();
                }
                // When Http response code is '500'
                else if (statusCode == 500) {
                  Toast.makeText(
                          getApplicationContext(),
                          "Something went wrong at server end",
                          Toast.LENGTH_LONG)
                      .show();
                }
                // When Http response code other than 404, 500
                else {
                  Toast.makeText(
                          getApplicationContext(),
                          "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]",
                          Toast.LENGTH_LONG)
                      .show();
                }
              }
            });
  }
  public void broadcastLocationFound(Location location) {

    String deviceId =
        Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);

    params = new RequestParams();
    params.put("UID", deviceId);
    params.put("LAT", Double.toString(location.getLatitude()));
    params.put("LON", Double.toString(location.getLongitude()));
    params.put("ACU", Double.toString(location.getAccuracy()));
    params.put("SPD", Double.toString(location.getSpeed()));

    PersistentCookieStore CookieStore = new PersistentCookieStore(LocationService.this);
    CookieStore.clear();
    AsyncHttpClient sendLocation = new AsyncHttpClient(false, 80, 443);
    sendLocation.setCookieStore(CookieStore);
    sendLocation.setTimeout(60000);
    sendLocation.post(
        url,
        params,
        new JsonHttpResponseHandler() {

          @Override
          public void onSuccess(
              int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.i(TAG, response.toString());
          }

          @Override
          public void onSuccess(
              int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) {
            super.onSuccess(statusCode, headers, response);
            Log.i(TAG, response.toString());
          }

          @Override
          public void onSuccess(
              int statusCode,
              cz.msebera.android.httpclient.Header[] headers,
              String responseString) {
            super.onSuccess(statusCode, headers, responseString);
            Log.i(TAG, responseString);
          }

          @Override
          public void onFailure(
              int statusCode,
              cz.msebera.android.httpclient.Header[] headers,
              String responseString,
              Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Log.v(TAG, responseString, throwable);
          }
        });
  }
  /** 上传图片 */
  private void savePicture(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] byte1 = baos.toByteArray();

    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("act", "imageup");
    params.put("soundtrack", new ByteArrayInputStream(byte1), "aa.jpeg"); // aa.jpeg 好像是随意
    client.post(Url.imageup, params, imageup_handler);
  }
示例#26
0
  private void restInvokeDelete(RequestParams params) {
    // Make RESTful webservice call using AsyncHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    client.delete(
        getApplicationContext(),
        domainAdress + DELETE_ROUTE,
        null,
        params,
        new AsyncHttpResponseHandler() {
          // When the response returned by REST has Http response code
          // '200'
          @Override
          public void onSuccess(int StatusCode, String answer) {
            try {
              JSONObject jO = new JSONObject(answer);
              if (jO.getBoolean("status")) {
                Toast.makeText(
                        getApplicationContext(), jO.getString(Consts.MSG_INFO), Toast.LENGTH_LONG)
                    .show();
                navigateToHomeActivity();

              } else {
                Toast.makeText(
                        getApplicationContext(), jO.getString(Consts.MSG_INFO), Toast.LENGTH_LONG)
                    .show();
              }
            } catch (JSONException e) {
              Toast.makeText(getApplicationContext(), R.string.invalidJSON, Toast.LENGTH_LONG)
                  .show();
              e.printStackTrace();
            }
          }

          // When the response returned by REST has Http response code
          // other than '200'
          @Override
          public void onFailure(int statusCode, Throwable error, String content) {

            // When Http response code is '404'
            if (statusCode == 404) {
              Toast.makeText(getApplicationContext(), R.string.err404, Toast.LENGTH_LONG).show();
            }
            // When Http response code is '500'
            else if (statusCode == 500) {
              Toast.makeText(getApplicationContext(), R.string.err500, Toast.LENGTH_LONG).show();
            }
            // When Http response code other than 404, 500
            else {
              Toast.makeText(getApplicationContext(), R.string.otherErr, Toast.LENGTH_LONG).show();
            }
          }
        });
  }
示例#27
0
  // http://192.168.2.4:9000/imgupload/upload_image.php
  // http://192.168.2.4:9999/ImageUploadWebApp/uploadimg.jsp
  // Make Http call to upload Image to Php server
  public void makeHTTPCall() {
    AsyncHttpClient client = new AsyncHttpClient();
    client.setTimeout(60000);
    // Don't forget to change the IP address to your LAN address. Port no as well.
    String URL = "http://hosamazzam.0fees.net/Blog_db_online/";
    //     URL="http://10.0.3.2/Blog_db/";

    if (type == "user") {

      client.post(
          URL + "db_upload.php",
          params,
          new AsyncHttpResponseHandler() {
            // When the response returned by REST has Http
            // response code '200'
            @Override
            public void onSuccess(String response) {
              // Hide Progress Dialog
              up.finish_uploading();
              System.out.println(response);
            }

            @Override
            public void onFailure(Throwable error, String content) {
              super.onFailure(error, content);
              System.out.println(content);
              up.failed();
            }
          });
    } else {
      client.post(
          URL + "db_upload_post.php",
          params,
          new AsyncHttpResponseHandler() {
            // When the response returned by REST has Http
            // response code '200'
            @Override
            public void onSuccess(String response) {
              // Hide Progress Dialog
              post.finish_uploading();
              System.out.println(response);
            }

            @Override
            public void onFailure(Throwable error, String content) {
              super.onFailure(error, content);
              //   System.out.println(content);
              post.failed();
            }
          });
    }
  }
  private void queryItems(Location location) {

    double latitude = 0;
    double longitude = 0;
    if (location != null) {
      latitude = location.getLatitude();
      longitude = location.getLongitude();
    }

    // Create a client to perform networking
    AsyncHttpClient client = new AsyncHttpClient();

    // Show ProgressDialog to inform user that a task in the background is occurring
    mDialog.show();

    // Have the client get a JSONArray of data
    // and define how to respond
    Log.i(TAG, QUERY_URL + "query?lat=" + latitude + "&lon=" + longitude);
    client.get(
        QUERY_URL + "query?lat=" + latitude + "&lon=" + longitude,
        new JsonHttpResponseHandler() {

          @Override
          public void onSuccess(JSONArray jsonArray) {
            // Dismiss the ProgressDialog
            mDialog.dismiss();
            // Display a "Toast" message
            // to announce your success
            Toast.makeText(getApplicationContext(), "Items updated!", Toast.LENGTH_LONG).show();
            Log.d(TAG, jsonArray.toString());

            mJSONAdapter.updateData(jsonArray);
          }

          @Override
          public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
            // Dismiss the ProgressDialog
            mDialog.dismiss();
            // Display a "Toast" message
            // to announce the failure
            Toast.makeText(
                    getApplicationContext(),
                    "Error: " + statusCode + " " + throwable.getMessage(),
                    Toast.LENGTH_LONG)
                .show();

            // Log error message
            // to help solve any problems
            Log.e(TAG, statusCode + " " + throwable.getMessage());
          }
        });
  }
 private void read() {
   // TODO Auto-generated method stub
   // 从网络获取数据并且调用Handler来添加到persons里面
   AsyncHttpClient client = new AsyncHttpClient();
   RequestParams params = new RequestParams();
   params.put("act", "list");
   params.put("uid", NApplication.userid);
   params.put("Participate", "0");
   params.put("PageSize", "" + PageSize);
   params.put("PageIndex", "" + PageIndex);
   params.put("IsParticipate", "0");
   Log.e("", Url.Operation + "?" + params);
   client.post(Url.Operation, params, DV_handler);
 }
示例#30
0
  // Method gets called when Broad Case is issued from MainActivity for every 10 seconds
  @Override
  public void onReceive(final Context context, Intent intent) {
    // TODO Auto-generated method stub
    noOfTimes++;
    Toast.makeText(context, "BC Service Running for " + noOfTimes + " times", Toast.LENGTH_SHORT)
        .show();
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    // Checks if new records are inserted in Remote MySQL DB to proceed with Sync operation
    client.post(
        "http://scottbm.5gbfree.com/webservice/mysqlsqlitesync/getdbrowcount.php",
        params,
        new AsyncHttpResponseHandler() {
          @Override
          public void onSuccess(String response) {
            System.out.println(response);
            try {
              // Create JSON object out of the response sent by getdbrowcount.php
              JSONObject obj = new JSONObject(response);
              System.out.println(obj.get("count"));
              // If the count value is not zero, call MyService to display notification
              if (obj.getInt("count") != 0) {
                final Intent intnt = new Intent(context, MyService.class);
                // Set unsynced count in intent data
                intnt.putExtra("intntdata", "Unsynced Rows Count " + obj.getInt("count"));
                // Call MyService
                context.startService(intnt);
              } else {
                Toast.makeText(context, "Sync not needed", Toast.LENGTH_SHORT).show();
              }
            } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }

          @Override
          public void onFailure(int statusCode, Throwable error, String content) {
            // TODO Auto-generated method stub
            if (statusCode == 404) {
              Toast.makeText(context, "404", Toast.LENGTH_SHORT).show();
            } else if (statusCode == 500) {
              Toast.makeText(context, "500", Toast.LENGTH_SHORT).show();
            } else {
              Toast.makeText(context, "Error occured!", Toast.LENGTH_SHORT).show();
            }
          }
        });
  }