示例#1
0
  void fetchLatestNews() {
    ConnectivityManager connectivityManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final Context context = this;
    if (connectivityManager.getActiveNetworkInfo().isConnected()) {
      Toast.makeText(this, R.string.info_fetching_news, Toast.LENGTH_SHORT).show();

      RequestQueue requestQueue = Volley.newRequestQueue(this);
      StringRequest request =
          new StringRequest(
              _mashableUrlString,
              new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                  MashableNews mashableNews = new Gson().fromJson(response, MashableNews.class);
                  _dataSet.addAll(mashableNews.newsItems);
                  _recyclerViewAdapter.notifyDataSetChanged();
                }
              },
              new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  Toast.makeText(
                          context,
                          R.string.error_fetching_news + error.getLocalizedMessage(),
                          Toast.LENGTH_SHORT)
                      .show();
                  Log.e("MainActivity", error.getMessage());
                }
              });
      requestQueue.add(request);
    } else {
      Toast.makeText(this, R.string.no_connection_when_fetching_news, Toast.LENGTH_SHORT).show();
    }
  }
示例#2
0
  private void showListIzv(final String uvjet, final String naziv) {
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            Config.LOGIN_WAMP_URL + "taskmeIzvjestajIspisZadatka.php",
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                List<String> klijent = Arrays.asList(response.split(","));

                arrayFinalTasks.addAll(klijent);
                adapter1.notifyDataSetChanged();
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {}
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            System.out.print("UVJET " + uvjet);
            System.out.print("NAZIV  " + naziv);
            params.put("UVJET", uvjet);
            params.put("IME", naziv);
            return params;
          }
        };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    System.out.println("request " + stringRequest);
    requestQueue.add(stringRequest);
  }
示例#3
0
  public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
      mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
  }
  private void retrieveCharacters() {

    Characters = new ArrayList<>();
    Response.Listener<JSONArray> successListener =
        new Response.Listener<JSONArray>() {
          @Override
          public void onResponse(JSONArray response) {
            parseJsonObjectToCharacter(response);
          }
        };

    Response.ErrorListener errorListener =
        new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError error) {
            System.out.println(error.getMessage());
          }
        };

    JSONObject request = null;
    String url = "http://walkingdead.rawb.xyz/api/walkingdead/GetCharacters?season=1&episode=1";

    JsonArrayRequest jsObjRequest =
        new JsonArrayRequest(url, request, successListener, errorListener);

    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
    queue.add(jsObjRequest);
  }
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   ViewUtils.inject(this);
   /*
    * 功能:获取前面activity传过来的uuid
    */
   Bundle bundle = getIntent().getExtras();
   uuid = bundle.getString("uuid");
   isOrigin = bundle.getBoolean("isOrigin");
   if (isOrigin) iv_inform_edit.setVisibility(View.VISIBLE);
   messageCount = bundle.getString("messageCount");
   volleyRequestQueue = Volley.newRequestQueue(this);
   context = InformActivity.this;
   loadingDialog = new LoadingDialog(context);
   loadingDialog.setLoadingString("请稍等");
   loadingDialog.showLoadingDialog();
   // 初始化
   init();
   /*
    * 功能:progress'判断网络状态的标志
    */
   //		progress = new ProgressDialog(InformActivity.this);
   //		progress.setMessage("请稍等");
   //		progress.setCanceledOnTouchOutside(false);
   //		progress.setCancelable(false);
   //		progress.show();
   // 获取后台数据
   NetConnect(uuid);
 }
示例#6
0
  @Override
  public void onCreate() {
    super.onCreate();

    // 初始化requestQueue对象
    requestQueue = Volley.newRequestQueue(this.getApplicationContext());

    int pid = android.os.Process.myPid();
    String processAppName = getAppName(pid);

    // 如果app启用了远程的service,此application:onCreate会被调用2次
    // 为了防止环信SDK被初始化2次,加此判断会保证SDK被初始化1次
    // 默认的app会在以包名为默认的process name下运行,如果查到的process name不是app的process name就立即返回

    if (processAppName == null || !processAppName.equalsIgnoreCase("com.caicai.criminalintent")) {
      Log.e(Config.TAG, "enter the service process!" + processAppName);
      // "com.easemob.chatuidemo"为demo的包名,换到自己项目中要改成自己包名
      // 则此application::onCreate 是被service 调用的,直接返回
      return;
    }

    // fresco初始化
    Fresco.initialize(this);

    EMChat.getInstance().init(this);

    // debugMode == true 时为打开,sdk 会在log里输入调试信息,在做代码混淆的时候需要设置成false
    EMChat.getInstance().setDebugMode(true); // 在做打包混淆时,要关闭debug模式,避免消耗不必要的资源
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    preferences = getSharedPreferences(null, 0);
    queue = Volley.newRequestQueue(this);

    boolean loggedIn = true;
    for (String data : userData) {
      if (!preferences.contains(data) || !preferences.getBoolean("isOnTeam", false)) {
        loggedIn = false;
        break;
      }
    }

    if (loggedIn) {
      Intent intent = new Intent(this, MainActivity.class);
      startActivity(intent);
      finish();
      return;
    }

    // If not logged in, create login activity
    setContentView(R.layout.activity_login);

    // Set up action bar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "Exo2-Medium.ttf");
    toolbarTitle.setTypeface(typeface);

    toolbar.setVisibility(View.GONE);
  }
示例#8
0
  @TargetApi(Build.VERSION_CODES.M)
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_computer);

    // Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    // Initializing our superheroes list
    listBookes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(this);

    // Calling method to get data to fetch data
    getData();

    // Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(this);

    // initializing our adapter
    adapter = new CardAdapter(listBookes, this);

    // Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
    setupActionBar();
  }
示例#9
0
  public CircleAdapter(Context ctx, List<CircleMessage> data) {
    mContext = ctx;
    this.data = data;

    RequestQueue mQueue = Volley.newRequestQueue(ctx);
    mImageLoader = new ImageLoader(mQueue, new BitmapCache());
  }
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_ticket_list);
    myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    // getActionBar().setDisplayHomeAsUpEnabled(true);
    hQueue = Volley.newRequestQueue(getApplicationContext());
    listTicks = (ListView) findViewById(R.id.lvTicket);
    btnRefresh = (Button) findViewById(R.id.btnRefreshTicket);
    btnSync = (Button) findViewById(R.id.btnSyncTicket);
    tvTLeft = (TextView) findViewById(R.id.tvTicketLeft);
    btnSync.setOnClickListener(onSyncClick);
    btnRefresh.setOnClickListener(onRefreshClick);

    getTickets();
    ArrayList ticketL = getListData();

    listTicks.setAdapter(new CustomListAdapterTickets(TicketListActivity.this, ticketL));

    listTicks.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Object o = listTicks.getItemAtPosition(i);
            Ticket newTicket = (Ticket) o;
          }
        });
    String ticCount = Long.toString(listTicks.getAdapter().getCount()) + " Tickets Left";
    tvTLeft.setText(ticCount);
  }
  @Override
  public void save(ShoppingCartItemModel model) {
    String url = "";

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    url = AppRetailDaoAbstract.URL_API + ShoppingCartItemModel.SHOPPING_CART_ITEM;

    Map<String, String> params = new HashMap<>();

    params.put("id", model.getId());
    params.put("idShoppingCart", model.getIdShoppingCart());
    params.put("idProduct", model.getIdProduct());
    params.put("status", model.getStatus());
    params.put("amountRequested", model.getAmountPurchased().toString());
    params.put("amountPurchased", model.getAmountPurchased().toString());
    params.put("unitPrice", model.getUnitValue().toString());
    params.put("pictureUrl", model.getPictureUrl());
    params.put("totalItem", model.getTotalItem().toString());

    HelperJsonArrayRequest jsArrRequest =
        new HelperJsonArrayRequest(
            Request.Method.PUT, url, params, view.getListener(), view.getErrorListener());

    requestQueue.add(jsArrRequest);
  }
示例#12
0
  public void login(final Context context, String login, final Intent intent) {
    String url = apiServerUrl + apiPath + loginPath + "?login="******"APIManager", "FailedLogin: " + error.getMessage());
              }
            });

    queue.add(stringRequest);
  }
示例#13
0
  public void rate(
      Context context, Response.Listener<String> responseListener, String eventID, float rate) {
    String url =
        apiServerUrl
            + apiPath
            + eventsPath
            + "/"
            + eventID
            + ratePath
            + "?rate="
            + String.valueOf(rate);
    RequestQueue queue = Volley.newRequestQueue(context);
    // Request a string response from the provided URL.
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            responseListener,
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.e("APIManager", "FailedRate: " + error.getMessage());
              }
            });

    queue.add(stringRequest);
  }
  private void volleyUpload() {

    try {
      String url = "http://192.168.1.33/upload/upload.php";

      HashMap<String, String> postData = new HashMap<>();
      postData.put("fname", "Rishi");
      postData.put("lname", "Jha");

      MultipartRequest obj =
          new MultipartRequest(
              url,
              new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError volleyError) {}
              },
              new Response.Listener<String>() {

                @Override
                public void onResponse(String s) {}
              },
              new File("/sdcard/Download/test.png"),
              postData);

      Volley.newRequestQueue(this).add(obj);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#15
0
 public RequestQueue getRequestQueue() {
   if (mRequestQueue == null) {
     mRequestQueue = Volley.newRequestQueue(this);
     mRequestQueue.start();
   }
   return mRequestQueue;
 }
  public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
      mRequestQueue = Volley.newRequestQueue(mCtx);
    }

    return mRequestQueue;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mVolleyRequestQueue = Volley.newRequestQueue(getActivity());
    intilizeStatic();
    mMovieAdapter = new MovieAdapter(getActivity(), null, 0);
    trailerDataModified.set(false);
    reviewDataModified.set(false);
    movieDetailsModified.set(false);
    movieMinutesModified.set(false);

    if (savedInstanceState != null) {
      synchronized (mMovieId) {
        mMovieId = savedInstanceState.getLong(sMovieIdKey);
        YouTubeFirstTrailerURL = savedInstanceState.getParcelable("ShareYoutubeLinkKey");
        if (YouTubeFirstTrailerURL != null)
          if (mShareActionProvider != null) {
            mMenu.findItem(R.id.action_share).setVisible(true);
          } else Log.e(LOG_TAG, "mShareActionProvider not set");
        try {
          mMovieId.notifyAll();
        } catch (IllegalMonitorStateException x) {
        }
      }
      Bundle b = new Bundle();
      b.putLong(sMovieIdKey, mMovieId);
      getLoaderManager().restartLoader(MovieQuery.DETAIL_LOADER, b, this);
      getLoaderManager().restartLoader(TrailerQuery.TRAILER_LOADER, b, this);
      getLoaderManager().restartLoader(ReviewQuery.REVIEW_LOADER, b, this);
    }
  }
示例#18
0
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   setContentView(R.layout.firstview);
   queue = Volley.newRequestQueue(this);
   super.onCreate(savedInstanceState);
   check = new Check();
 }
示例#19
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   activity = getActivity();
   mQueue = Volley.newRequestQueue(activity);
 }
  void SetLock() {
    String l = new String("lock");
    Response.Listener<String> listener =
        new Response.Listener<String>() {
          @Override
          public void onResponse(String response) {
            try {
              // Log.i("tagconvertstr", "[" + response + "]");
              JSONObject jsonObject = new JSONObject(response);
              boolean success = jsonObject.getBoolean("success");

              if (success) {

                Toast.makeText(getApplication(), "Lock Set", Toast.LENGTH_SHORT).show();

              } else {
                Toast.makeText(getApplication(), "Lock Error", Toast.LENGTH_SHORT).show();
              }
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        };

    Lockrequest lr = new Lockrequest(l, listener);
    RequestQueue queue = Volley.newRequestQueue(getApplication());
    queue.add(lr);
  }
示例#21
0
 @Override
 protected void onHandleIntent(Intent intent) {
   String url = null;
   String userName = intent.getStringExtra(PROVIDED_USER_NAME);
   String instrumentName = intent.getStringExtra(PROVIDED_INSTRUMENT);
   try {
     url = URLDecoder.decode(getString(R.string.poll_post_url, instrumentName, userName), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   if (url == null) return;
   RequestFuture<String> future = RequestFuture.newFuture();
   StringRequest request = new StringRequest(Request.Method.POST, url, future, future);
   Volley.newRequestQueue(getApplicationContext()).add(request);
   try {
     String response = future.get(30, TimeUnit.SECONDS);
     PostPollDto dto = new Gson().fromJson(response, PostPollDto.class);
     if (dto.getStatus().toLowerCase().equalsIgnoreCase("ok")) {
       PreferencesUtil.savePollInstrument(getApplicationContext(), instrumentName);
       PreferencesUtil.saveUserName(getApplicationContext(), userName);
       EventBus.getDefault().post(new PollPostEvent());
     } else {
       EventBus.getDefault().post(new PollPostEvent(dto.getMsg()));
     }
   } catch (InterruptedException | ExecutionException | TimeoutException e) {
     EventBus.getDefault().post(new PollPostEvent(e.getLocalizedMessage()));
   }
 }
示例#22
0
  private void initRequestHelpers() {
    queue = Volley.newRequestQueue(this);

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Game.class, new TwitchResultItemParser());
    gson = builder.create();
  }
  @Override
  protected Boolean doInBackground(Void... params) {
    HashMap<String, String> hashMap = new HashMap<>();
    hashMap.put("action", status);

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    JsonObjectRequest request =
        new JsonObjectRequest(Request.Method.PATCH, URL, new JSONObject(hashMap), null, null) {
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("REST-API-TOKEN", pID);
            headers.put("X-HTTP-Method-Override", "PATCH");
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("User-agent", System.getProperty("http.agent"));
            return headers;
          }

          @Override
          protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            System.out.println(response.statusCode);

            success = response.statusCode == 200;

            return super.parseNetworkResponse(response);
          }
        };
    requestQueue.add(request);

    return success;
  }
  /**
   * @Declaration : - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
   * completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError
   * *error))completionHandler @Description : Creates an HTTP request for the specified URL request
   * object, and calls a handler upon completion.
   *
   * @param request An NSURLRequest object that provides the URL, cache policy, request type, body
   *     data or body stream, and so on.
   * @param completionHandler The completion handler to call when the load request is complete. This
   *     handler is executed on the delegate queue. Unless you have provided a custom delegate, this
   *     parameter must not be nil, because there is no other way to retrieve the response data.
   * @return Return Value The new session data task. @Discussion After you create the task, you must
   *     start it by calling its resume method.
   */
  public NSURLSessionDataTask dataTaskWithRequestCompletionHandler(
      NSURLRequest request,
      final PerformBlock.VoidBlockNSDataNSURLResponseNSError completionHandler) {
    RequestQueue queue = Volley.newRequestQueue(GenericMainContext.sharedContext);
    JsonObjectRequest jsonRequest =
        new JsonObjectRequest(
            Request.Method.GET,
            request.URL.getUrlString().getWrappedString(),
            new JSONObject(),
            new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(JSONObject response) {
                try {
                  completionHandler.perform(
                      new NSData(response.toString().getBytes("UTF-8")),
                      new NSURLResponse().initWithJSONResponse(response),
                      new NSError());
                } catch (UnsupportedEncodingException e) {
                  Log.d(NSURLSession.class.getSimpleName(), String.valueOf(e));
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
              }
            });
    queue.add(jsonRequest);

    return new NSURLSessionDataTask(request.URL);
  }
示例#25
0
  public void makeArrayType() {
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            Config.LOGIN_WAMP_URL + "taskmeTipZadatkaCitanje.php",
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                // If we are getting success from server
                List<String> useri = Arrays.asList(response.split(","));
                arrayTask.clear();
                arrayTask.addAll(useri);
                adapter1.notifyDataSetChanged();

                System.out.print("iz respons e" + Arrays.asList(arrayTask));
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                System.out.print("error: " + error.toString());
              }
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            return null;
          }
        };
    // Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
  }
示例#26
0
 public static void setupVolleyQueue() {
   requestQueue = Volley.newRequestQueue(mContext, VolleyUtils.getHTTPClientStack(mContext));
   imageLoader = new ImageLoader(requestQueue, getBitmapCache());
   VolleyLog.setTag(AppLog.TAG);
   // http://stackoverflow.com/a/17035814
   imageLoader.setBatchedResponseDelay(0);
 }
示例#27
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RequestQueue queue = Volley.newRequestQueue(getActivity());
    // http://www.omdbapi.com/?plot=short&amp;r=json&amp;i=
    String url = getString(R.string.episode_detail_url) + getImDBId();

    final EpisodeBaseActivity baseActivity = (EpisodeBaseActivity) getActivity();
    baseActivity.showLoadingIndicator();

    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                EpisodeDetails episodeDetails =
                    EpisodeDetailResponseParser.parseEpisodeDetails(response);

                if (episodeDetails != null) {
                  TextView valYear = (TextView) getActivity().findViewById(R.id.valYear);
                  valYear.setText(episodeDetails.getYear());

                  TextView valRated = (TextView) getActivity().findViewById(R.id.valRated);
                  valRated.setText(episodeDetails.getRated());

                  TextView valReleased = (TextView) getActivity().findViewById(R.id.valReleased);
                  valReleased.setText(episodeDetails.getReleasedDate());

                  TextView valSeason = (TextView) getActivity().findViewById(R.id.valSeason);
                  valSeason.setText(episodeDetails.getSeasonNumber());

                  TextView valEpisode = (TextView) getActivity().findViewById(R.id.valEpisode);
                  valEpisode.setText(episodeDetails.getEpisodeNumber());

                  TextView valRuntime = (TextView) getActivity().findViewById(R.id.valRuntime);
                  valRuntime.setText(episodeDetails.getRunDuration());

                  getActivity().setTitle(episodeDetails.getTitle());
                  baseActivity.hideLoadingIndicator();
                } else {
                  baseActivity.showErrorDialog(
                      getString(R.string.errorAlertTitle), getString(R.string.errorMessage));
                  baseActivity.hideLoadingIndicator();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                baseActivity.hideLoadingIndicator();
                baseActivity.showErrorDialog(
                    getString(R.string.errorAlertTitle), getString(R.string.errorMessage));
              }
            });
    queue.add(stringRequest);
  }
  public void checkSession() {
    final SharedPreferences sharedPref =
        getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    final String sessionToken =
        sharedPref.getString(getString(R.string.preference_session_token), null);

    if (sessionToken == null) return;

    // Resposta de sucesso
    Response.Listener<JSONObject> successListener =
        new Response.Listener<JSONObject>() {
          @Override
          public void onResponse(JSONObject responseJson) {
            Log.d(LOG_TAG, "Success");
            Log.d(LOG_TAG, responseJson.toString());
            hideProgressDialog();

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString(getString(R.string.preference_user_object), responseJson.toString());
            editor.commit();

            Intent intent = new Intent(MainActivity.this, DashboardActivity.class);
            startActivity(intent);
            finish();
          }
        };

    // Resposta de erro
    Response.ErrorListener errorListener =
        new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError volleyError) {
            Log.d(LOG_TAG, "Erro");
            Log.d(LOG_TAG, volleyError.toString());
            hideProgressDialog();
          }
        };

    // Envia requisição
    showProgressDialog();

    JsonObjectRequest request =
        new JsonObjectRequest(
            Request.Method.GET, ApiEndpoints.SESSION_INFO, successListener, errorListener) {
          @Override
          public HashMap<String, String> getHeaders() {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("Authentication-Token", sessionToken);
            return params;
          }
        };
    request.setRetryPolicy(
        new DefaultRetryPolicy(
            ApiEndpoints.TIMEOUT,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(request);
  }
示例#29
0
文件: City.java 项目: mytime/Map
  public void getDate(Context context, String url) {

    StringRequest request =
        new StringRequest(
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String s) {
                // 输出
                Log.i("info", s);

                // 解析json数据
                try {
                  dealData(s);
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError volleyError) {}
            });
    try {
      Volley.newRequestQueue(context.getApplicationContext()).add(request);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
      mRequestQueue = Volley.newRequestQueue(punjitApplication.getInstance());
    }

    return mRequestQueue;
  }