com.android.volley.toolbox.StringRequest Java Examples
The following examples show how to use
com.android.volley.toolbox.StringRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Act_NewHttpClient.java From android_volley_examples with Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act__new_http_client); mTvResult = (TextView) findViewById(R.id.tv_result); Button btnSimpleRequest = (Button) findViewById(R.id.btn_simple_request); btnSimpleRequest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Usually getting the request queue shall be in singleton like in {@see Act_SimpleRequest} // Current approach is used just for brevity RequestQueue queue = Volley .newRequestQueue(Act_NewHttpClient.this, new ExtHttpClientStack(new DefaultHttpClient())); StringRequest myReq = new StringRequest(Method.GET, "http://www.google.com/", createMyReqSuccessListener(), createMyReqErrorListener()); queue.add(myReq); } }); }
Example #2
Source File: VolleyManager.java From EventApp with Apache License 2.0 | 6 votes |
public void get(String url, final ResponseListener listener) { StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String s) { listener.onResponse(s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { listener.onError(volleyError); } } ); mRequestQueue.add(request); }
Example #3
Source File: MainActivity.java From codeexamples-android with Eclipse Public License 1.0 | 6 votes |
public void onClick(View view) { final TextView mTextView = (TextView) findViewById(R.id.result); // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(this); String url = "http://www.vogella.com"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { mTextView.setText("Response is: " + response.substring(0, 500)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mTextView.setText("That didn't work!"); } }); // Add the request to the RequestQueue. queue.add(stringRequest); }
Example #4
Source File: GoodsDetailActivity.java From school_shop with MIT License | 6 votes |
private void loadData(){ stringRequest = new StringRequest(URLs.MARKET_COMMENTLIST_URL+goodsEntity.getId(), new Response.Listener<String>() { @Override public void onResponse(String response) { jsonData = response; parseJson(); goodsDetailAdapter.notifyDataSetChanged(); } } , new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); stringRequest.setTag(stringRequestTag); requestQueue.add(stringRequest); }
Example #5
Source File: FindListFragment.java From school_shop with MIT License | 6 votes |
private void loadData() { stringRequest = new StringRequest(URLs.MARK_LIST, new Response.Listener<String>() { @Override public void onResponse(String response) { parseJson(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { showToastError(error.toString()); } }); stringRequest.setTag(stringRequestTag); requestQueue.add(stringRequest); }
Example #6
Source File: TabooProxy.java From MaterialCalendar with Apache License 2.0 | 6 votes |
public static void fetchJSContent() { RequestQueue requestQueue = RQManager.getInstance().getRequestQueue(); for (int i = (SAVEYEAR - 10); i < (SAVEYEAR + 10); i++) { final String datePrefix = String.valueOf(i); StringRequest stringRequest = new StringRequest(Method.GET, FETCHURL + datePrefix + ".js", new Response.Listener<String>() { @Override public void onResponse(String response) { String result = response.substring(response.indexOf("=") + 1, response.length() - 3) + "]"; try { AssetJSONLoad.json2file(datePrefix + ".json", result); } catch (IOException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { /* TODO Auto-generated method stub */ } }); requestQueue.add(stringRequest); } requestQueue.start(); }
Example #7
Source File: VolleyUtil.java From android-common-utils with Apache License 2.0 | 6 votes |
/** * send a request to server and callback * * @param method the method ,see {@link com.android.volley.Request.Method} * @param url the url * @param params the request params, can be null. * @param tag the tag to cancel * @param callback the callback */ public static void sendRequest(int method, final String url, final ApiParams params, Object tag, final VolleyUtil.HttpCallback callback) { StringRequest request = new StringRequest(method, url, new Response.Listener<String>() { @Override public void onResponse(String response) { logIfNeed(url,response); callback.onResponse(url, response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { logIfNeed(url, error.getMessage()); callback.onErrorResponse(url, error); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { return params; } }; executeRequest(request,tag); }
Example #8
Source File: RequestSingletonFactory.java From Netease with GNU General Public License v3.0 | 6 votes |
public StringRequest getPOSTStringRequest(Context context, String url, final Map<String, String> paramsMap, Response.Listener responseListener) { return new StringRequest(Request.Method.POST, url, responseListener, new DefaultErrorListener(context)) { @Override protected Map<String, String> getParams() throws AuthFailureError { return paramsMap; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String str = null; addEncodeing2Request(response); return super.parseNetworkResponse(response); } // Volley请求类提供了一个 getHeaders()的方法,重载这个方法可以自定义HTTP 的头信息。(也可不实现) @Override public Map<String, String> getHeaders() throws AuthFailureError{ return defaultPairs_baishuku_mobile; } // @Override // protected String getParamsEncoding() { // return "GBK"; // } }; }
Example #9
Source File: RemoteConnectUtil.java From zap-android with MIT License | 6 votes |
public static void decodeConnectionString(Context ctx, String data, OnRemoteConnectDecodedListener listener) { if (UriUtil.isLNDConnectUri(data)) { decodeLndConnectString(ctx, data, listener); } else if (data.startsWith("config=")) { // URL to BTCPayConfigJson String configUrl = data.replace("config=", ""); StringRequest btcPayConfigRequest = new StringRequest(Request.Method.GET, configUrl, response -> decodeBtcPay(ctx, response, listener), error -> listener.onError(ctx.getResources().getString(R.string.error_unableToFetchBTCPayConfig), RefConstants.ERROR_DURATION_SHORT)); ZapLog.debug(LOG_TAG, "Fetching BTCPay config..."); HttpClient.getInstance().addToRequestQueue(btcPayConfigRequest, "BTCPayConfigRequest"); } else if (BTCPayConfigParser.isValidJson(data)) { // Valid BTCPay JSON decodeBtcPay(ctx, data, listener); } else { listener.onNoConnectData(); } }
Example #10
Source File: WebService.java From ExamplesAndroid with Apache License 2.0 | 6 votes |
public void QueryGet(final String title) {//Pasamos los parametros final RequestQueue queue = Volley.newRequestQueue(context);//Creamos instancia de RequestQueue con el contexto como parametro String url = "http://www.omdbapi.com/?t="+title+"&y=&plot=short&r=json";//Colocamos la URL,concatenando el parametro StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {//Hacemos la peticion @Override public void onResponse(String response) {//Se es correcta OK Log.e("response: ", response);//Se mostrara en la consola la cadena con los valores obtenidos } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error: ", error.getMessage() + "");//Se mostrara en la consola la cadena de error } }); queue.add(stringRequest); }
Example #11
Source File: UserFragment.java From android-kubernetes-blockchain with Apache License 2.0 | 6 votes |
public void sendStepsToMongo(String userId, int numberOfStepsToSend) { StringRequest stringRequest = new StringRequest(Request.Method.POST, BACKEND_URL + "/registerees/update/" + userId + "/steps/" + String.valueOf(numberOfStepsToSend), new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response); Log.d(TAG, "Steps updated in mongo"); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, "That didn't work!"); } }); this.queue.add(stringRequest); }
Example #12
Source File: RequestQueueTest.java From volley with Apache License 2.0 | 6 votes |
@Test public void cancelAll_onlyCorrectTag() throws Exception { RequestQueue queue = new RequestQueue(new NoCache(), mMockNetwork, 0, mDelivery); Object tagA = new Object(); Object tagB = new Object(); StringRequest req1 = mock(StringRequest.class); when(req1.getTag()).thenReturn(tagA); StringRequest req2 = mock(StringRequest.class); when(req2.getTag()).thenReturn(tagB); StringRequest req3 = mock(StringRequest.class); when(req3.getTag()).thenReturn(tagA); StringRequest req4 = mock(StringRequest.class); when(req4.getTag()).thenReturn(tagA); queue.add(req1); // A queue.add(req2); // B queue.add(req3); // A queue.cancelAll(tagA); queue.add(req4); // A verify(req1).cancel(); // A cancelled verify(req3).cancel(); // A cancelled verify(req2, never()).cancel(); // B not cancelled verify(req4, never()).cancel(); // A added after cancel not cancelled }
Example #13
Source File: CacheDispatcherTest.java From volley with Apache License 2.0 | 6 votes |
@Test public void tripleCacheMiss_networkErrorOnFirst() throws Exception { StringRequest secondRequest = new StringRequest(Request.Method.GET, "http://foo", null, null); StringRequest thirdRequest = new StringRequest(Request.Method.GET, "http://foo", null, null); mRequest.setSequence(1); secondRequest.setSequence(2); thirdRequest.setSequence(3); mDispatcher.processRequest(mRequest); mDispatcher.processRequest(secondRequest); mDispatcher.processRequest(thirdRequest); verify(mNetworkQueue).put(mRequest); verifyNoResponse(mDelivery); ((Request<?>) mRequest).notifyListenerResponseNotUsable(); // Second request should now be in network queue. verify(mNetworkQueue).put(secondRequest); // Another unusable response, third request should now be added. ((Request<?>) secondRequest).notifyListenerResponseNotUsable(); verify(mNetworkQueue).put(thirdRequest); }
Example #14
Source File: VolleyUtil.java From android-common-utils with Apache License 2.0 | 6 votes |
public static void post(final String url, final ApiParams params, Object tag, final HttpCallback callback) { executeRequest(new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { logIfNeed(url, response); callback.onResponse(url, response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { logIfNeed(url, error.getMessage()); callback.onErrorResponse(url, error); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { return params; } }, tag); }
Example #15
Source File: VolleyRequestManager.java From HttpRequestProcessor with Apache License 2.0 | 6 votes |
@Override public void get(String url, final IRequestCallback requestCallback) { StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String s) { requestCallback.onSuccess(s); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { requestCallback.onFailure(volleyError); } }); HttpRequestExampleApp.mQueue.add(request); }
Example #16
Source File: VolleyProcessor.java From HttpRequestProcessor with Apache License 2.0 | 6 votes |
@Override public void post(String url, Map<String, Object> params, final ICallBack callback) { StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { callback.onSuccess(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { callback.onFailed(volleyError.toString()); } }); mQueue.add(stringRequest); }
Example #17
Source File: LocalSearch.java From MapsSDK-Native with MIT License | 6 votes |
static void sendRequest(Context context, String query, GeoboundingBox bounds, Callback callback) { if (query == null || query.isEmpty()) { Toast.makeText(context, "Invalid query", Toast.LENGTH_LONG).show(); return; } String boundsStr = String.format(Locale.ROOT, "%.6f,%.6f,%.6f,%.6f", bounds.getSouth(), bounds.getWest(), bounds.getNorth(), bounds.getEast()); RequestQueue queue = Volley.newRequestQueue(context); queue.add(new StringRequest( Request.Method.GET, URL_ENDPOINT.replace("{query}", query).replace("{bounds}", boundsStr), (String response) -> { List<Poi> results = parse(response); if (results == null || results.isEmpty()) { callback.onFailure(); return; } callback.onSuccess(results); }, (VolleyError error) -> callback.onFailure() )); }
Example #18
Source File: LoginFragment.java From Anti-recall with GNU Affero General Public License v3.0 | 6 votes |
private void sendMsg() { RequestQueue queue = Volley.newRequestQueue(getContext()); StringRequest request = new StringRequest(Request.Method.POST, "http://ar.qsboy.com/j/applyCaptcha", response -> { Log.i(TAG, "sendMsg: " + response); captcha = response; }, error -> Log.e(TAG, "sendMsg: " + error)) { @Override protected Map<String, String> getParams() { Map<String, String> map = new HashMap<>(); map.put("phone", phone); return map; } }; queue.add(request); }
Example #19
Source File: SendMail.java From ExamplesAndroid with Apache License 2.0 | 5 votes |
public void EnviarMail(final Email email) { final RequestQueue queue = Volley.newRequestQueue(context); StringRequest postRequest = new StringRequest(Request.Method.POST, SendMailPHP,new Response.Listener<String>() { @Override public void onResponse(String response) { Toast.makeText(context,"EMAIL Enviado",Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, "Error al enviar el EMAIL " + error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("emisor", email.getEmisor()); params.put("receptor", email.getReceptor()); params.put("asunto", email.getAsunto()); params.put("mensaje", email.getMensaje()); return params; } }; queue.add(postRequest); }
Example #20
Source File: KCommands.java From kboard with GNU General Public License v3.0 | 5 votes |
public void curl(int n, String parameter) { // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(mIme); final int repeat = n; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, parameter, new Response.Listener<String>() { @Override public void onResponse(String response) { i(repeat, response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override public Map<String, String> getHeaders(){ Map<String, String> headers = new HashMap<>(); headers.put("User-agent", "curl"); headers.put("Accept", "text/plain"); return headers; } }; // Add the request to the RequestQueue. queue.add(stringRequest); }
Example #21
Source File: MainActivity.java From android-https-volley with Apache License 2.0 | 5 votes |
private void createHttpRequestUsedToVolley() { VolleyListener listener = new VolleyListener(); RequestQueue queue = Volley.newRequestQueue(this, new SslHttpStack(new SslHttpClient(getBaseContext(), 44400))); StringRequest request = new StringRequest( Request.Method.GET, REQUEST_URL, listener, listener); queue.add(request); }
Example #22
Source File: RequestToolsSimple.java From BigApp_WordPress_Android with Apache License 2.0 | 5 votes |
private <T> void makeStringRequest(final String url, int requestMethod, final Object requestObject, String tag) { Log.e("", "wenjun request makeStringRequest url = " + url); StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("", "wenjun request makeStringRequest response = " + response); mListener.success(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mListener.error(error, true); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); if (!url.contains(RequestUrl.login) && BaseApplication.getCookies() != null) { headers.put("Cookie", BaseApplication.getCookies()); } return headers; } }; req.setShouldCache(false); BaseApplication.getInstance().addToRequestQueue(req, tag); }
Example #23
Source File: UPnPDiscovery.java From android-upnp-discovery with MIT License | 5 votes |
private void getData(final String url, final UPnPDevice device) { StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { device.update(response); mListener.OnFoundNewDevice(device); devices.add(device); mThreadsCount--; if (mThreadsCount == 0) { mActivity.runOnUiThread(new Runnable() { public void run() { mListener.OnFinish(devices); } }); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mThreadsCount--; Log.d(TAG, "URL: " + url + " get content error!"); } }); stringRequest.setTag(TAG + "SSDP description request"); Volley.newRequestQueue(mContext).add(stringRequest); }
Example #24
Source File: KCommands.java From kboard with GNU General Public License v3.0 | 5 votes |
public void curl(int n, String parameter) { // Instantiate the RequestQueue. RequestQueue queue = Volley.newRequestQueue(mIme); final int repeat = n; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, parameter, new Response.Listener<String>() { @Override public void onResponse(String response) { i(repeat, response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override public Map<String, String> getHeaders(){ Map<String, String> headers = new HashMap<>(); headers.put("User-agent", "curl"); headers.put("Accept", "text/plain"); return headers; } }; // Add the request to the RequestQueue. queue.add(stringRequest); }
Example #25
Source File: FindImageUrlLoader.java From myapplication with Apache License 2.0 | 5 votes |
/** * 获得第page页图片url * @param page 页数 */ public void loadImageUrl(int page) { String dataUrl = String.format(DATA_URL, dataType, count, page); StringRequest request = new StringRequest(dataUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject obj = new JSONObject(response); JSONArray array = obj.getJSONArray("results"); imageUrlList.clear(); for (int i = 0; i < array.length(); i++) { String url = array.getJSONObject(i).getString("url");//获得图片url imageUrlList.add(url); } callback.addData(imageUrlList); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //加载出错 Log.e(TAG, "error:" + error.getMessage()); Toast.makeText(context, "加载出错", Toast.LENGTH_SHORT).show(); } }); request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT, 1, 1.0f));//设置请求超时 BasicApplication.getInstance().addRequest(request);//将消息添加到消息队列 }
Example #26
Source File: Api.java From magnet-client with Mozilla Public License 2.0 | 5 votes |
/** * Perform an HTTP request. * * @param url * @param callback */ private void request(int method, String url, final String body, final Callback callback) { getQueue().add(new StringRequest(method, url, new Response.Listener<String>() { @Override public void onResponse(String response) { callback.resolve(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.reject(error.toString()); } }){ @Override public byte[] getBody() throws AuthFailureError { if (body == null) { return null; } return body.getBytes(); } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); map.put("Content-Type", "application/json; charset=UTF-8"); return map; } }); }
Example #27
Source File: StringRequestFragment.java From VolleyX with Apache License 2.0 | 5 votes |
void refreshItems() { final StringRequest request = new StringRequest(URL, null, null); VolleyX.from(request).subscribeOn(Schedulers.io()) .map(new Func1<String, List<Music>>() { @Override public List<Music> call(String s) { return mapper.transformJsonToMusicCollection(s); } }).map(new Func1<List<Music>, Pair<DiffUtil.DiffResult, List<Music>>>() { @Override public Pair<DiffUtil.DiffResult, List<Music>> call(List<Music> musics) { return Pair.create(DiffUtil.calculateDiff(new MusicListDiffCallback(mAdapter.getDatas(), musics)), musics); } }).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Pair<DiffUtil.DiffResult, List<Music>>>() { @Override public void onCompleted() { Log.d(TAG, "onCompleted"); mSwipeRefreshLayout.setRefreshing(false); } @Override public void onError(Throwable e) { Log.d(TAG, "onError " + Log.getStackTraceString(e)); mSwipeRefreshLayout.setRefreshing(false); } @Override public void onNext(Pair<DiffUtil.DiffResult, List<Music>> result) { Log.d(TAG, "onNext"); mAdapter.setDatas(result.second); result.first.dispatchUpdatesTo(mAdapter); } }); }
Example #28
Source File: LoginFragment.java From Anti-recall with GNU Affero General Public License v3.0 | 5 votes |
private boolean verifyCaptcha(String captcha) { RequestQueue queue = Volley.newRequestQueue(getContext()); RequestFuture future = RequestFuture.newFuture(); StringRequest request = new StringRequest(Request.Method.POST, "http://ar.qsboy.com/j/verifyCaptcha", future, future) { @Override protected Map<String, String> getParams() { Map<String, String> map = new HashMap<>(); map.put("phone", phone); map.put("captcha", captcha); return map; } }; queue.add(request); try { String s = (String) future.get(5, TimeUnit.SECONDS); boolean isValid = s != null && s.length() > 0; if (isValid) { Gson gson = new Gson(); gson.fromJson(s, App.User.class); } return isValid; } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); return false; } }
Example #29
Source File: MarketListFragment.java From school_shop with MIT License | 5 votes |
/** * * @author Owater * @createtime 2015-3-24 下午5:59:09 * @Decription 开始加载数据 * * @param postion viewpager的位置,代表类别 */ private void loadingData(int postion,int beforeId){ jsonData = null; String userId = null; if(MyApplication.userInfo!=null){ userId = MyApplication.userInfo[1]; } String url = URLs.MARKET_GOODSLIST_URL+postion+"&beforeId="+beforeId+"&schoolId="+schoolId+"&userId="+userId; Log.i(TAG,"MARKET_GOODSLIST_URL=="+url); stringRequest = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.i(TAG,"response=="+response); jsonData=response; parseJson(); resetLoading(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { showToastError(error.toString()); mfooUpdate.showFail("加载失败,点击重新加载"); resetLoading(); } }); stringRequest.setTag(stringRequestTag); requestQueue.add(stringRequest); }
Example #30
Source File: SelfRouteDetailActivity.java From kute with Apache License 2.0 | 5 votes |
private void requestServer(final String url){ final StringRequest mrequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { //Parse the response from server if(is_progress_dialog_visible){ progress_dialog.dismiss(); } Log.d(TAG,"Response from server :" +response); Intent i=new Intent(getBaseContext(), Main.class); startActivity(i); finish(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //give an option to retry Log.d(TAG,"volley Error "+error.toString()); showMessageTryCancel("Confirmation to server failed..Try Again!",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { requestServer(url); } }); } }); request_queue.add(mrequest); if(!is_progress_dialog_visible) { is_progress_dialog_visible = true; progress_dialog.show(); } }