예제 #1
0
  private String doRequest(int method, String relativeUrl, final Map<String, String> params) {
    final String url = baseUrl + relativeUrl;
    StringRequest sr;
    String response;

    RequestFuture<String> future = RequestFuture.newFuture();
    if (params != null) {
      sr =
          new StringRequest(method, url, future, future) {
            @Override
            protected Map<String, String> getParams() {
              return params;
            }
          };
    } else {
      sr = new StringRequest(method, url, future, future);
    }

    Log.v(DEBUG_TAG, "StringRequest " + sr.getUrl());
    queue.add(sr);

    try {
      response = future.get(30, TimeUnit.SECONDS);
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
      e.printStackTrace();
      return null;
    }

    return response;
  }
예제 #2
0
  public void getRideEstimates() {
    MyVolley.init(context);
    RequestQueue queue = MyVolley.getRequestQueue();
    StringRequest myReq =
        new StringRequest(
            Request.Method.GET,
            "https://api.uber.com/v1/estimates/price",
            reqSuccessListenerFoodList(),
            reqErrorListenerFoodList()) {

          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("server_token", "maMItAGDV5HHqKAG3nLfLTlhMOnQscAONF_aeFcu");
            return headers;
          }

          protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();

            params.put("start_latitude", String.valueOf((float) 28.613939));
            params.put("start_longitude", String.valueOf((float) 77.209021));
            params.put("end_latitude", String.valueOf((float) 28.7499));
            params.put("end_longitude", String.valueOf((float) 77.1170));

            return params;
          }
        };
    myReq.setRetryPolicy(new DefaultRetryPolicy(25000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(myReq);
  }
 /**
  * post请求方式 1url 2StringRequest 3重写getParams方法,返回map型数据 4requset写tag 5将请求添加到队列中
  *
  * <p>聚合数据 wifi appkey:28ed2359d895a71cbe106812afb6d6a0
  * http://apis.juhe.cn/wifi/local?key=appkey&lon=116.366324&lat=39.905859&r=3000&type=1
  */
 private void volley_post() {
   String url = "http://apis.juhe.cn/wifi/local?";
   StringRequest request =
       new StringRequest(
           Request.Method.POST,
           url,
           new Response.Listener<String>() {
             @Override
             public void onResponse(String s) {
               Toast.makeText(VolleyActivity.this, s + "", Toast.LENGTH_SHORT).show();
             }
           },
           new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError volleyError) {
               Toast.makeText(VolleyActivity.this, volleyError.toString(), Toast.LENGTH_SHORT)
                   .show();
             }
           }) {
         @Override
         protected Map<String, String> getParams() throws AuthFailureError {
           HashMap<String, String> map = new HashMap<>();
           // key=appkey&lon=116.366324&lat=39.905859&r=3000&type=1
           map.put("lon", "116.366324");
           map.put("lat", "39.905859");
           map.put("type", "1");
           map.put("key", "28ed2359d895a71cbe106812afb6d6a0");
           return map;
         }
       };
   request.setTag("volley_post");
   BaseApplication.getRequestQueue().add(request);
 }
예제 #4
0
  public void sendTokenRequest() {
    progressWheel.setVisibility(View.VISIBLE);
    RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            getRequestUrl(),
            new Response.Listener<String>() {
              @Override
              public void onResponse(String s) {
                progressWheel.setVisibility(View.GONE);
                Log.e("Value", s);
                preferenceClass.saveAccessToken(s);
                if (preferenceClass.getAccessToken() != null
                    && preferenceClass.getAccessToken().length() != 0) {
                  sendLoginJsonRequest();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError volleyError) {
                if (volleyError instanceof TimeoutError
                    || volleyError instanceof NoConnectionError) {
                  Snackbar.make(
                          loginLayout,
                          "Something is wrong with your internet connection. Please check your settings",
                          Snackbar.LENGTH_LONG)
                      .show();

                } else if (volleyError instanceof AuthFailureError) {
                  // TODO
                } else if (volleyError instanceof ServerError) {
                  hideKeyboard();
                  Snackbar.make(
                          loginLayout,
                          "We are facing problems in connecting to our servers. Just chill and try after some time :)",
                          Snackbar.LENGTH_LONG)
                      .show();
                } else if (volleyError instanceof NetworkError) {
                  Snackbar.make(
                          loginLayout,
                          "Something is wrong with your internet connection. Please check your settings",
                          Snackbar.LENGTH_LONG)
                      .show();

                } else if (volleyError instanceof ParseError) {

                  // TODO
                }
              }
            });
    stringRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            9000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(stringRequest);
  }
예제 #5
0
  // Método encargado de realizar peticiones de creación, modificación o eliminación de un usuario
  // y que recibe como parámetro de entrada la URI para realizar dicha petición al servicio web.
  public void peticionServicioUsuario(String uri) {
    // Se declara e inicializa una variable de tipo RequestQueue, encargada de crear
    // una nueva petición en la cola del servicio web.
    RequestQueue queue = Volley.newRequestQueue(getActivity());

    // Se declara e inicializa un objeto de tipo StringRequest, que permite recuperar un
    // String a partir de la URL que recibe. El constructor de la clase StringRequest
    // recibe como argumentos de entrada el método para que el cliente realice operaciones
    // sobre el servicio web, la uri para el acceso al recurso, la interfaz Response.Listener,
    // encargada de devolver la respuesta parseada a la petición del cliente, y la interfaz
    // Response.ErrorListener encargada de entregar una respuesta errónea desde el servicio web.
    StringRequest sRequest =
        new StringRequest(
            Request.Method.GET,
            uri,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                try {
                  // Nuevo usuario insertado o Usuario borrado correctamente
                  Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                try {
                  Toast.makeText(
                          getActivity(),
                          "Error en la petición de servicio de usuario: " + error.toString(),
                          Toast.LENGTH_LONG)
                      .show();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });

    // Se definen las políticas para la petición realizada. Recibe como argumento una
    // instancia de la clase DefaultRetryPolicy, que recibe como parámetros de entrada
    // el tiempo inicial de espera para la respuesta, el número máximo de intentos,
    // y el multiplicador de retardo de envío por defecto.
    sRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            15000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    // Se añade la petición a la cola con el objeto de tipo JsonArrayRequest.
    queue.add(sRequest);
  }
 // this method retrieves new settings data from remote server
 private void getNewSettingsData() {
   requestGetNewSettings =
       new StringRequest(
           Request.Method.GET,
           urlGetNewSettingsData,
           new Response.Listener<String>() {
             @Override
             public void onResponse(String response) {
               requestGetNewSettings.markDelivered();
               response = response.replace("\\", "");
               try {
                 JSONObject jsonObject = new JSONObject(response);
                 networkStatus = "good";
                 for (int i = 0; i < jsonObject.names().length(); i++) {
                   String keyName = jsonObject.names().getString(i);
                   editorAppSettings.putString(keyName, jsonObject.getString(keyName));
                 }
                 editorAppSettings.commit();
               } catch (JSONException e) {
                 e.printStackTrace();
               }
             }
           },
           new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
               requestGetNewSettings.markDelivered();
               Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
             }
           });
   requestGetNewSettings.setRetryPolicy(
       new DefaultRetryPolicy(
           3000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
   MySingletonRequestQueue.getInstance(context).add(requestGetNewSettings);
 }
예제 #7
0
  private void GetStringRequest() {
    String url = "www.baidu.com";
    StringRequest request =
        new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {}
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {}
            });

    request.setTag(TAG);
    MyApplication.getHttpQueue().add(request);
  }
예제 #8
0
  private void volley_Post() {
    String url = "";
    StringRequest request =
        new StringRequest(
            Request.Method.POST,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String s) {}
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError volleyError) {}
            });
    request.setTag("");
    MyApplication.getHttpQueues().add(request);
  }
예제 #9
0
  /**
   * @description 获取用户请求
   * @param context
   * @param userstring
   */
  public static void VolleyGetRate(final Context context, final String userstring) {

    String url = Constant.httpUrl + "ResultsController";
    StringRequest request =
        new StringRequest(
            Method.POST,
            url,
            new Listener<String>() {

              @Override
              public void onResponse(String string) {
                // 解析JSON数据
                List<Result> list = Result.ParseJSON_Rate_grade(string);
                List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
                for (Result result : list) {
                  HashMap<String, Object> item = new HashMap<String, Object>();
                  item.put("rate_grade", result.getRate_grade());
                  data.add(item);
                }
                // handler异步消息处理
                Message msg = new Message();
                msg.what = 0x124;
                msg.obj = data;
                ShowResultActivity.handler.sendMessage(msg);
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(context, "网络请求失败", Toast.LENGTH_LONG).show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("operation", "queryrategrade");
            params.put("username", userstring);
            return params;
          }
        };
    request.setTag("GetRate");
    App.getHttpQueue().add(request);
  }
  private void init() {
    String url = AppConfig.URL_SHOP + "product/getProdPicDetail";
    JSONObject params = new JSONObject();
    try {
      params.put("prodUuid", prodUuid);
    } catch (Exception e) {
      // TODO: handle exception
    }
    StringRequest stringRequest =
        new StringRequest(
            Method.POST,
            url,
            params,
            new Listener<String>() {

              @Override
              public void onResponse(String response) {
                // TODO Auto-generated method stub
                try {
                  JSONArray jsonArray = new JSONArray(response);
                  imageViews = new ArrayList<String>();
                  for (int i = 0; i < jsonArray.length(); i++) {
                    imageViews.add(jsonArray.getJSONObject(i).getString("picUrl"));
                  }
                  gv_goods_pic_details.setAdapter(
                      new GoodsDetailsAdapter(getActivity(), imageViews));
                } catch (JSONException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              }
            },
            new ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub

              }
            });
    stringRequest.setTag("getPicDetails");
    MyApplication.getRequestQueue().add(stringRequest);
  }
예제 #11
0
  /**
   * @description 发送异常通知请求
   * @param context
   * @param userstring
   * @param nickstring
   * @param time
   * @param rate_grade
   * @param symptoms_rhythm
   * @param symptoms_heart
   */
  public static void VolleyAbnormalNotice(
      final Context context,
      final String userstring,
      final String nickstring,
      final String time,
      final String rate_grade,
      final String symptoms_rhythm,
      final String symptoms_heart) {

    String url = Constant.httpUrl + "SmsServlet";
    StringRequest request =
        new StringRequest(
            Method.POST,
            url,
            new Listener<String>() {

              @Override
              public void onResponse(String string) {}
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(context, "网络请求失败", Toast.LENGTH_LONG).show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("operation", "sendnotice");
            params.put("username", userstring);
            params.put("nick", nickstring);
            params.put("time", time);
            params.put("rate_grade", rate_grade);
            params.put("symptoms_rhythm", symptoms_rhythm);
            params.put("symptoms_heart", symptoms_heart);
            return params;
          }
        };
    request.setTag("AbnormalNotice");
    App.getHttpQueue().add(request);
  }
예제 #12
0
  private void initContent() {
    content = (TextView) findViewById(R.id.content);

    Map<String, String> params = new HashMap<>();
    params.put("studentId", BaseApplication.getStudentLoginInfo().getStudentId());
    params.put("roleNum", BaseApplication.getStudentLoginInfo().getRoleNum());
    StringRequest request =
        new StringRequest(
            Request.Method.POST,
            PostUtils.mergeUrlActionParams("getGrxxMobile", params),
            response -> {
              try {
                JSONObject jsonObject = new JSONArray(response).getJSONObject(0);
                String[] strs = jsonObject.getString("str").split(",");
                content.setText(
                    Utils.getAndFormatCharSequence(
                        this,
                        R.string.content_info,
                        strs[1],
                        strs[2],
                        strs[3],
                        strs[4],
                        strs[5],
                        strs[6],
                        strs[7],
                        strs[8],
                        strs[9],
                        strs[10]));
                findViewById(R.id.progress_overlay).setVisibility(View.GONE);
              } catch (JSONException e) {
                CrashReport.postCatchedException(e);
              }
            },
            e -> {
              CrashReport.postCatchedException(e);
              Toast.makeText(this, R.string.error_network_timeout, Toast.LENGTH_SHORT).show();
              finish();
            });
    request.setTag(TAG);
    BaseApplication.getRequestQueue().add(request);
  }
예제 #13
0
  public void sendRequest(final CustomPath path, final Context context) {
    this.context = context;
    cp = path;
    RequestQueue queue = Volley.newRequestQueue(context);
    StringRequest sr =
        new StringRequest(
            Request.Method.POST,
            JSON_URL,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                savePath(response);
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
              }
            }) {

          public String getBodyContentType() {
            return "application/json; charset=" + getParamsEncoding();
          }

          public byte[] getBody() throws AuthFailureError {
            try {

              String test = new GsonBuilder().create().toJson(path);
              return test.getBytes(getParamsEncoding());
            } catch (UnsupportedEncodingException | ConcurrentModificationException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            return null;
          }
        };
    sr.setRetryPolicy(new DefaultRetryPolicy(10000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(sr);
  }
예제 #14
0
  /**
   *
   *
   * <pre>
   * 1. 기능 : String 반환 타입 API 요청
   * 2. 처리개요 :
   *     - String 반환 타입 API 요청 기능을 수행한다.
   * 3. 주의사항 :
   * ===================================
   * 4. 작성자/작성일 : 이동식 / 2014. 11. 11.
   * ===================================
   * 5. 수정사항
   * 5.1 요구사항 ID :
   *     - 수정자/수정일 :
   *     - 수정사유/내역 :
   * ===================================
   * </pre>
   *
   * @param context Context 객체
   * @param url 요청 URL
   * @param requestType 요청 HTTP METHOD TYPE
   * @param handler 요청결과 처리 핸들러
   * @param succMsg 성공 메시지 상수
   * @param failMsg 실패 메시지 상수
   * @param requestPersonalId 요청 personal id
   */
  public void requestString(
      Context context,
      String url,
      int requestType,
      Handler handler,
      int succMsg,
      int failMsg,
      final String requestPersonalId) {
    boolean isDismissDialog = false;
    if (context != null) {
      // UICommonUtil.getInstance(context).showProgressDialog(context);
      CommonProgressDialog.showProgressDialog(context);
      isDismissDialog = true;
    }

    StringRequest stringRequest =
        new StringRequest(
            requestType,
            url,
            new StringSuccessListener(handler, isDismissDialog, succMsg),
            new ErrorListener(handler, isDismissDialog, failMsg)) {

          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();

            headers.put(HTTP_HEADER_ACCEPT_LANGUAGE, Locale.getDefault().getLanguage());
            if (requestPersonalId != null && requestPersonalId.length() > 0) {
              headers.put(HTTP_HEADER_PERSONAL_ID, requestPersonalId);
            } else if (personalId != null && personalId.length() > 0) {
              headers.put(HTTP_HEADER_PERSONAL_ID, personalId);
            }
            return headers;
          }
        };
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 0));
    stringRequest.setTag(NETWORK_REQUEST_TAG);
    queue.add(stringRequest);
  }
 /**
  * 1url 2StringRequest 请求 3request.setTag 4把请求添加到队列
  *
  * <p>http://apis.juhe.cn/cook/query?key=dd63cca81dbbc59deaf7b7f6be0383e2&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3
  */
 private void volley_get() {
   String url =
       "http://apis.juhe.cn/cook/query?key=dd63cca81dbbc59deaf7b7f6be0383e2&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3";
   StringRequest request =
       new StringRequest(
           Request.Method.GET,
           url,
           new Response.Listener<String>() {
             @Override
             public void onResponse(String s) {
               Toast.makeText(VolleyActivity.this, s + "", Toast.LENGTH_SHORT).show();
             }
           },
           new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError volleyError) {
               Toast.makeText(VolleyActivity.this, volleyError.toString(), Toast.LENGTH_SHORT)
                   .show();
             }
           });
   request.setTag("volley_get");
   BaseApplication.getRequestQueue().add(request);
 }
예제 #16
0
  private void volley_Get() {
    String url = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=";
    StringRequest request =
        new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String s) {

                Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
              }
            });
    request.setTag("abcGet");
    MyApplication.getHttpQueues().add(request);
  }
 private void compareUpdateTimestamp() {
   // get local last settings update timestamp, for new installed app, it's 0
   final long lastUpdateTimestamp = spAppSettings.getLong("lastUpdateTimestamp", 0);
   // compare the local timestamp with the one retrieving from remote server
   requestCheckLastUpdateTimestamp =
       new StringRequest(
           Request.Method.GET,
           urlCheckLastUpdateTimestamp,
           new Response.Listener<String>() {
             @Override
             public void onResponse(String response) {
               requestCheckLastUpdateTimestamp.markDelivered();
               response = response.replace("\\", "");
               try {
                 JSONObject jsonObject = new JSONObject(response);
                 long remoteLastSettingsUpdateTimestamp = jsonObject.getLong("last update");
                 if (remoteLastSettingsUpdateTimestamp > lastUpdateTimestamp) {
                   editorAppSettings
                       .putLong("lastUpdateTimestamp", remoteLastSettingsUpdateTimestamp)
                       .commit();
                   getNewSettingsData();
                 } else {
                   networkStatus = "good";
                 }
               } catch (JSONException e) {
                 e.printStackTrace();
               }
             }
           },
           new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
               requestCheckLastUpdateTimestamp.markDelivered();
               Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
             }
           });
   requestCheckLastUpdateTimestamp.setRetryPolicy(
       new DefaultRetryPolicy(
           3000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
   MySingletonRequestQueue.getInstance(context)
       .add(requestCheckLastUpdateTimestamp); // execute request
 }
예제 #18
0
  public void login() {

    Log.d(TAG, "Login");
    // ensures that fields are correct by calling validate method
    // Toast.makeText(getApplicationContext(), "Will make login POST request soon!",
    // Toast.LENGTH_SHORT).show();
    Toast.makeText(
            getApplicationContext(),
            "User Login Status: " + session.isLoggedIn(),
            Toast.LENGTH_LONG)
        .show();

    final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this, R.style.AppTheme);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Authenticating...");
    progressDialog.show();

    if (!validate()) {
      onLoginFailed(progressDialog);
      return;
    }

    _loginButton.setEnabled(false);

    // get fields and TODO: insert into HTTP POST request below
    final String email = _emailText.getText().toString();
    final String password = _passwordText.getText().toString();
    // TODO: Implement your own authentication logic here. (make HTTP POST request to
    // <server>/oauth/token)
    // JSON {"username":"******", "password":"******" or "Bob12345"}

    StringRequest jsonObjectRequest =
        new StringRequest(
            Request.Method.POST,
            LOGIN_URL,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                Log.d(TAG, "Valid Response: " + response.toString());

                try {
                  // Parsing json object response
                  JSONObject j = new JSONObject(response);
                  jsonResponse = "";
                  String token = j.getString("access_token");
                  jsonResponse += "Access token: " + token + "\n\n";
                  Log.d(TAG, jsonResponse);
                  session.createLoginSession(email, token);
                  onLoginSuccess();

                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error Response: " + error.toString());
                onLoginFailed(progressDialog);

                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                  Log.d(TAG, "Timeout/no connection error: " + error.toString());
                  Toast.makeText(
                      getBaseContext(),
                      "Please make sure you have internet connection",
                      Toast.LENGTH_LONG);
                } else if (error instanceof AuthFailureError) {
                  Log.d(TAG, "AuthFailure error: " + error.toString());
                } else if (error instanceof ServerError) {
                  Log.d(TAG, "Server error: " + error.toString());
                } else if (error instanceof NetworkError) {
                  Log.d(TAG, "Network error: " + error.toString());
                } else if (error instanceof ParseError) {
                  Log.d(TAG, "Parse error: " + error.toString());
                }
              }
            }) {
          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_PASSWORD, password);
            params.put(KEY_EMAIL, email);
            params.put(KEY_GRANT_TYPE, "password");
            Log.d("Params", "params: " + params.toString());
            return params;
          }

          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/json");
            return headers;
          }

          @Override
          public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=utf-8";
          }
        };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonObjectRequest);
    Log.d(TAG, jsonObjectRequest.toString());
  }
예제 #19
0
  public static void SignUPUser(RequestQueue requestQueue) {

    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            Endpoints.getRequestUrlSignUp(50),
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                //  Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();

                L.m("response" + response);

                // DataModel dataModel = DataModel.getInstance();
                //  dataModel.setStatus("sss");
                try {
                  L.m("inside try");

                  JSONObject jsonResponse = new JSONObject(response);
                  SignUpResponseModel signUpResponseModel = Parser.parseSignUptJSON(jsonResponse);

                  Log.d("inside signup user", "inside signup user:"******"inside catch");
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.d("sign up error", "errot", error);
                // Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("device_id", "ddd");
            params.put("name", "ddd");
            params.put("email", "*****@*****.**");
            params.put("msisdn", "8882405463");
            params.put("gender", "male");
            params.put("dob", "15021990");
            /*   params.put(KEY_PASSWORD,password);
            params.put(KEY_EMAIL, email);*/
            return params;
          }
        };
    stringRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            50000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(stringRequest);

    /*
            JSONObject response = RequestorData.requestHomeDataJSON(requestQueue, Endpoints.getRequestUrlSignUp(50));
    */

    //  MyApplication.getWritableDatabase().insertMovies(DBMovies.BOX_OFFICE, listMovies, true);
  }
  public void execute() {
    // final TextView textView = (TextView) activity.findViewById(R.id.textView);
    Cache cache = new DiskBasedCache(context.getCacheDir(), 1024 * 1024); // 1MB cap
    final Network network = new BasicNetwork(new HurlStack());
    mRequestQueue = new RequestQueue(cache, network);
    mRequestQueue.start();
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {

              @Override
              public void onResponse(String response) {
                if (response != null
                    && !response.equalsIgnoreCase("null")
                    && !response.equalsIgnoreCase("\"Not found !\"")) {
                  ParseNotificationData parseNotificationData = new ParseNotificationData(response);
                  NotificationData notificationData = parseNotificationData.parse();
                  Log.d("NOT", notificationData.getId());
                  Log.d("NOT", notificationData.getTextMessage());
                  SharedPreferences sharedPreferences =
                      PreferenceManager.getDefaultSharedPreferences(
                          context.getApplicationContext());
                  String language =
                      sharedPreferences.getString(
                          context.getResources().getString(R.string.prefrance_language_key),
                          context.getResources().getString(R.string.pref_language_default));

                  SharedPreferences.Editor editor = sharedPreferences.edit();
                  switch (language) {
                    case "1":
                      if (sharedPreferences.getString("arabic_id", "-11").equals("-11"))
                        editor.putString("arabic_id", notificationData.getId());
                      else if (Integer.parseInt(notificationData.getId())
                          > Integer.parseInt(sharedPreferences.getString("arabic_id", "1"))) {
                        MyNotification myNotification = new MyNotification(context);
                        myNotification.notify(notificationData.getTextMessage());
                        editor.putString("arabic_id", notificationData.getId());
                      }
                      break;
                    case "2":
                      if (sharedPreferences.getString("franch_id", "-11").equals("-11"))
                        editor.putString("franch_id", notificationData.getId());
                      else if (Integer.parseInt(notificationData.getId())
                          > Integer.parseInt(sharedPreferences.getString("franch_id", "1"))) {
                        MyNotification myNotification = new MyNotification(context);
                        myNotification.notify(notificationData.getTextMessage());
                        editor.putString("franch_id", notificationData.getId());
                      }
                      break;
                    case "3":
                      if (sharedPreferences.getString("english_id", "-11").equals("-11"))
                        editor.putString("english_id", notificationData.getId());
                      else if (Integer.parseInt(notificationData.getId())
                          > Integer.parseInt(sharedPreferences.getString("english_id", "1"))) {
                        MyNotification myNotification = new MyNotification(context);
                        myNotification.notify(notificationData.getTextMessage());
                        editor.putString("english_id", notificationData.getId());
                      }
                      break;
                  }
                  editor.commit();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                // Handle erro
                // Toast.makeText(activity, "Error in network connection",
                // Toast.LENGTH_LONG).show();
              }
            });
    // stringRequest.setShouldCache(false);
    stringRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            2 * 1000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    mRequestQueue.add(stringRequest);
  }
예제 #21
0
  /**
   * @description 发送结果请求
   * @param context
   * @param userstring
   * @param nickstring
   * @param time
   * @param rate_grade
   * @param symptoms_rhythm
   * @param rate_average
   * @param rate_min
   * @param rate_max
   * @param rhythm_heart
   * @param sinus_arrest
   * @param cardia_heart
   * @param heart_beat_number
   * @param psvc_number
   * @param pvc_number
   * @param qRS
   * @param rR
   * @param qT
   * @param pR
   * @param qTC
   * @param symptoms_heart
   * @param symptoms_heart_left
   * @param symptoms_heart_right
   * @param symptoms_heart_two
   */
  public static void VolleySendResult(
      final Context context,
      final String userstring,
      final String nickstring,
      final String time,
      final String rate_grade,
      final String symptoms_rhythm,
      final String rate_average,
      final String rate_min,
      final String rate_max,
      final String rhythm_heart,
      final String sinus_arrest,
      final String cardia_heart,
      final String heart_beat_number,
      final String psvc_number,
      final String pvc_number,
      final String qRS,
      final String rR,
      final String qT,
      final String pR,
      final String qTC,
      final String symptoms_heart,
      final String symptoms_heart_left,
      final String symptoms_heart_right,
      final String symptoms_heart_two) {

    String url = Constant.httpUrl + "ResultsController";
    StringRequest request =
        new StringRequest(
            Method.POST,
            url,
            new Listener<String>() {

              @Override
              public void onResponse(String string) {}
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(context, "网络请求失败", Toast.LENGTH_LONG).show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("operation", "addresult");
            params.put("username", userstring);
            params.put("nick", nickstring);
            params.put("time", time);
            params.put("rate_grade", rate_grade);
            params.put("symptoms_rhythm", symptoms_rhythm);
            params.put("rate_average", rate_average);
            params.put("rate_min", rate_min);
            params.put("rate_max", rate_max);
            params.put("rhythm_heart", rhythm_heart);
            params.put("sinus_arrest", sinus_arrest);
            params.put("cardia_heart", cardia_heart);
            params.put("heart_beat_number", heart_beat_number);
            params.put("psvc_number", psvc_number);
            params.put("pvc_number", pvc_number);
            params.put("QRS", qRS);
            params.put("RR", rR);
            params.put("QT", qT);
            params.put("PR", pR);
            params.put("QTC", qTC);
            params.put("symptoms_heart", symptoms_heart);
            params.put("symptoms_heart_left", symptoms_heart_left);
            params.put("symptoms_heart_right", symptoms_heart_right);
            params.put("symptoms_heart_two", symptoms_heart_two);

            Log.v("TAG", "userstring:" + userstring);
            Log.v("TAG", "nickstring:" + nickstring);

            return params;
          }
        };
    request.setTag("SendResult");
    App.getHttpQueue().add(request);
  }
예제 #22
0
  /**
   * @description 获取结果请求
   * @param context
   * @param userstring
   */
  public static void VolleyGetResult(final Context context, final String userstring) {

    String url = Constant.httpUrl + "ResultsController";
    StringRequest request =
        new StringRequest(
            Method.POST,
            url,
            new Listener<String>() {

              @Override
              public void onResponse(String string) {
                List<Result> list = Result.ParseJSON(string);
                List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
                for (Result result : list) {
                  HashMap<String, Object> item = new HashMap<String, Object>();
                  item.put("time", result.getTime());
                  item.put("nick", result.getNick());
                  item.put("rate_grade", result.getRate_grade());
                  item.put("symptoms_rhythm", result.getSymptoms_rhythm());
                  item.put("rate_average", result.getRate_average());
                  item.put("rate_min", result.getRate_min());
                  item.put("rate_max", result.getRate_max());
                  item.put("rhythm_heart", result.getRhythm_heart());
                  item.put("sinus_arrest", result.getSinus_arrest());
                  item.put("cardia_heart", result.getCardia_heart());
                  item.put("heart_beat_number", result.getHeart_beat_number());
                  item.put("psvc_number", result.getPsvc_number());
                  item.put("pvc_number", result.getPvc_number());
                  item.put("QRS", result.getQRS());
                  item.put("RR", result.getRR());
                  item.put("QT", result.getQT());
                  item.put("PR", result.getPR());
                  item.put("QTC", result.getQTC());
                  item.put("symptoms_heart", result.getSymptoms_heart());
                  item.put("symptoms_heart_left", result.getSymptoms_heart_left());
                  item.put("symptoms_heart_right", result.getSymptoms_heart_right());
                  item.put("symptoms_heart_two", result.getSymptoms_heart_two());
                  data.add(item);
                }
                // handler异步消息处理
                Message msg = new Message();
                msg.what = 0x124;
                msg.obj = data;
                ResultFragment.handler.sendMessage(msg);
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(context, "网络请求失败", Toast.LENGTH_LONG).show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("operation", "queryresult");
            params.put("username", userstring);
            return params;
          }
        };
    request.setTag("GetResult");
    App.getHttpQueue().add(request);
  }
 public boolean hasHadResponseDelivered() {
   return (requestCheckLastUpdateTimestamp.hasHadResponseDelivered()
       && (requestGetNewSettings == null || requestGetNewSettings.hasHadResponseDelivered()));
 }
 public void cancelSettingsRequest() {
   if (!requestCheckLastUpdateTimestamp.hasHadResponseDelivered()
       && !requestCheckLastUpdateTimestamp.isCanceled()) requestCheckLastUpdateTimestamp.cancel();
   if (!requestGetNewSettings.hasHadResponseDelivered() && !requestGetNewSettings.isCanceled())
     requestGetNewSettings.cancel();
 }
  private void sendComment(final String creator, final String meldung) {

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = ServerConnection.SERVERURL + "SetComment.php";

    progressDialog = ProgressDialog.show(this, "", "Sende Kommentar...", false, true);

    // Request a string response from the provided URL.
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                // Display the first 500 characters of the response string.
                progressDialog.dismiss();

                Intent intent = new Intent(AddCommentActivity.this, CommentActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("newsId", mNewsId);
                intent.putExtra("title", mTitle);
                intent.putExtra("date", mDate);
                intent.putExtra("body", mBody);
                intent.putExtra("newsTag", mNewsTag);
                startActivity(intent);
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();

                AlertDialog.Builder b = new AlertDialog.Builder(AddCommentActivity.this);
                b.setTitle(android.R.string.dialog_alert_title);
                b.setMessage("Es konnte keine Verbindung hergestellt werden");
                b.setPositiveButton(
                    getString(android.R.string.ok),
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dlg, int arg1) {
                        dlg.dismiss();
                      }
                    });
                b.create().show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("newsID", Integer.toString(mNewsId));
            params.put("creator", creator);
            params.put("body", meldung);
            return params;
          }
        };
    stringRequest.setTag(this);
    stringRequest.setRetryPolicy(
        new DefaultRetryPolicy(10000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(stringRequest);
  }
예제 #26
0
  private void editUser(
      final String userid,
      final String height,
      final String suku,
      final String agama,
      final String rokok,
      final String alkohol,
      final String horoskop,
      final String pekerjaan,
      final String descdiri,
      final String tipe_psg,
      final String kegiatan,
      final String lokasi,
      final String suka,
      final String malming) {
    final ProgressDialog progressDialog = new ProgressDialog(EditProfile.this);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Please wait...");
    progressDialog.show();
    String xetns = "";
    String xpkrj = "";
    String xlksi = "";
    try {
      xetns = txtRace.getSelectedItem().toString();
      xpkrj = txtJob.getSelectedItem().toString();
      xlksi = txtLocation.getSelectedItem().toString();
    } catch (Exception e) {
      Log.d("error", "spin " + e.getMessage());
    }
    final String etns = xetns;
    final String agm = txtReligion.getSelectedItem().toString();
    final String mrk = txtRokok.getSelectedItem().toString();
    final String alkh = txtAlkohol.getSelectedItem().toString();
    final String hrskp = txtHoroscope.getSelectedItem().toString();
    final String pkrj = xpkrj;
    final String lksi = xlksi;
    if (etns.equals("") || pkrj.equals("") || lksi.equals("")) {
      AlertDialog infoPass = new AlertDialog.Builder(EditProfile.this).create();
      infoPass.setTitle("Perhatian");
      infoPass.setMessage("Silahkan cek koneksi anda");
      infoPass.setButton(
          AlertDialog.BUTTON_NEUTRAL,
          "OK",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              progressDialog.dismiss();
              dialog.dismiss();
            }
          });
      infoPass.setButton(
          AlertDialog.BUTTON_NEGATIVE,
          "Coba Lagi",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              progressDialog.dismiss();
              editUser(
                  userid, height, suku, agama, rokok, alkohol, horoskop, pekerjaan, descdiri,
                  tipe_psg, kegiatan, lokasi, suka, malming);
            }
          });
      infoPass.show();
    } else {

      StringRequest requestDaftar =
          new StringRequest(
              Request.Method.POST,
              AppConfig.urlAPI,
              new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                  progressDialog.dismiss();

                  try {
                    JSONObject jsonResponse = new JSONObject(response);
                    // ambil nilai dari JSON respon API
                    String jodiStatus = jsonResponse.getString("status");

                    if (jodiStatus.equals("success")) {
                      sessions.changeValueRegister("edit_profile", 1);
                      db.updateUser(
                          userid, etns, agm, height, lksi, hrskp, pkrj, descdiri, mrk, alkh,
                          tipe_psg, kegiatan, suka, malming);
                      if (fromActivity.equals("profile")) {
                        Intent i = new Intent(getApplicationContext(), Profile.class);
                        startActivity(i);
                        finish();
                      } else {
                        Intent i = new Intent(getApplicationContext(), imageUpload.class);
                        i.putExtra("fromActivity", "EditProfile");
                        startActivity(i);
                        finish();
                      }
                    } else {
                      Toast.makeText(EditProfile.this, jodiStatus, Toast.LENGTH_LONG).show();
                    }

                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }
              },
              new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                  Toast.makeText(
                          EditProfile.this, "Please check your connection", Toast.LENGTH_LONG)
                      .show();
                }
              }) {
            protected Map<String, String> getParams() {
              Map<String, String> params = new HashMap<String, String>();
              // parameter, nilai
              params.put("userid", userid);
              params.put("height", height);
              params.put("suku", suku);
              params.put("agama", agama);
              params.put("rokok", rokok);
              params.put("alkohol", alkohol);
              params.put("horoskop", horoskop);
              params.put("pekerjaan", pekerjaan);
              params.put("descdiri", descdiri);
              params.put("tipe_psg", tipe_psg);
              params.put("kegiatan", kegiatan);
              params.put("lokasi", lokasi);
              params.put("suka", suka);
              params.put("malming", malming);
              params.put("jodiEditProfile", "");

              return params;
            }
          };
      RequestQueue requestQueue = Volley.newRequestQueue(this);
      requestQueue.add(requestDaftar);
      requestDaftar.setRetryPolicy(
          new DefaultRetryPolicy(
              60000,
              DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
              DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
  }
  public void getEtiquette(
      final Context context,
      String url,
      ListView lv,
      EtiquetteListAdapter ad,
      ArrayList<Etiquette> list,
      Map<String, String> params,
      boolean dialog) {
    listView = lv;
    etiquetteListAdapter = ad;
    etiquetteArrayList = list;
    parameters = params;
    showDialog = dialog;

    StringRequest postRequest =
        new StringRequest(
            Request.Method.POST,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                try {
                  if (showDialog) {
                    progressDialog.dismiss();
                    progressDialog = null;
                  }

                  if (MainActivity.gps.canGetLocation()) {
                    // MainActivity.location = MainActivity.gps.getLocation();

                  } else {
                    // Can't get location.
                    // GPS or network is not enabled.
                    // Ask user to enable GPS/network in settings.
                    if (MainActivity.askGps) {
                      MainActivity.askGps = false;
                      MainActivity.gps.showSettingsAlert();
                    }
                  }

                  JSONObject jsonResponse = new JSONObject(response);
                  String msg = jsonResponse.getString("status");

                  if (msg.equals("success")) {
                    Gson gson = new Gson();
                    Etiquette[] result =
                        gson.fromJson(jsonResponse.getString("data"), Etiquette[].class);
                    etiquetteArrayList.clear();
                    etiquetteListAdapter.clear();
                    etiquetteArrayList.addAll(Arrays.asList(result));
                    etiquetteListAdapter.notifyDataSetChanged();
                    MainActivity.showDialog = false;
                  } else {
                    etiquetteListAdapter.clear();
                    etiquetteListAdapter.notifyDataSetChanged();
                  }

                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                if (showDialog) {
                  progressDialog.dismiss();
                  progressDialog = null;
                }
                if (MainActivity.gps.canGetLocation()) {
                  // MainActivity.location = MainActivity.gps.getLocation();

                } else {
                  // Can't get location.
                  // GPS or network is not enabled.
                  // Ask user to enable GPS/network in settings.
                  if (MainActivity.askGps) {
                    MainActivity.gps.showSettingsAlert();
                    MainActivity.askGps = false;
                  }
                }
                Toast.makeText(context, "Check internet connection", Toast.LENGTH_SHORT).show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() {
            return parameters;
          }
        };

    RetryPolicy policy =
        new DefaultRetryPolicy(
            30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);

    if (showDialog) {
      progressDialog = new TransparentProgressDialog(context, R.drawable.loading3);
      progressDialog.show();
    }

    MainActivity.networkQueue.add(postRequest);
  }