Java Code Examples for com.android.volley.toolbox.StringRequest

The following examples show how to use com.android.volley.toolbox.StringRequest. These examples are extracted from open source projects. 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 Project: MapsSDK-Native   Source File: LocalSearch.java    License: MIT License 6 votes vote down vote up
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 2
Source Project: codeexamples-android   Source File: MainActivity.java    License: Eclipse Public License 1.0 6 votes vote down vote up
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 3
Source Project: android_volley_examples   Source File: Act_NewHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: zap-android   Source File: RemoteConnectUtil.java    License: MIT License 6 votes vote down vote up
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 5
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 6
Source Project: volley   Source File: RequestQueueTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: volley   Source File: CacheDispatcherTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: HttpRequestProcessor   Source File: VolleyRequestManager.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: HttpRequestProcessor   Source File: VolleyProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
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 11
Source Project: android-common-utils   Source File: VolleyUtil.java    License: Apache License 2.0 6 votes vote down vote up
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 12
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 13
Source Project: ExamplesAndroid   Source File: WebService.java    License: Apache License 2.0 6 votes vote down vote up
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 14
Source Project: MaterialCalendar   Source File: TabooProxy.java    License: Apache License 2.0 6 votes vote down vote up
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 15
Source Project: school_shop   Source File: FindListFragment.java    License: MIT License 6 votes vote down vote up
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 16
Source Project: school_shop   Source File: GoodsDetailActivity.java    License: MIT License 6 votes vote down vote up
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 17
Source Project: EventApp   Source File: VolleyManager.java    License: Apache License 2.0 6 votes vote down vote up
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 18
Source Project: android-common-utils   Source File: VolleyUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 19
Source Project: BaldPhone   Source File: S.java    License: Apache License 2.0 5 votes vote down vote up
public static void sendVersionInfo(final Context context) {
    if (!S.isEmulator() && !BuildConfig.DEBUG) {
        final SharedPreferences sharedPreferences = BPrefs.get(context);
        if (!sharedPreferences.contains(BPrefs.UUID_KEY)) {
            sharedPreferences.edit().putString(BPrefs.UUID_KEY, UUID.randomUUID().toString()).apply();
        }

        final RequestQueue requestQueue = Volley.newRequestQueue(context);

        requestQueue.add(
                new StringRequest(
                        Request.Method.GET,
                        "https://raw.githubusercontent.com/UriahShaulMandel/BaldPhone/master/logging%20mechanism/loga.txt",
                        response -> {
                            requestQueue.add(
                                    new StringRequest(
                                            Request.Method.GET,
                                            String.format(Locale.US, "%s?uuid=%s&vcode=%d&locale=%s&flavor=%s", response, sharedPreferences.getString(BPrefs.UUID_KEY, null), BuildConfig.VERSION_CODE, String.valueOf(Locale.getDefault()), BuildConfig.FLAVOR),
                                            response2 -> {
                                            },
                                            error2 -> {
                                            }
                                    ).setTag("baldphone_server"));
                        },
                        error -> {
                        }
                ).setTag("baldphone_get_server_info"));

    }
}
 
Example 20
Source Project: jus   Source File: VolleyFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void standardQueueStringRequest(View v) {
	final TextView mTextView = (TextView) v.findViewById(R.id.tv_string_request);

	// StringRequest with VOLLEY with Standard RequestQueue
	// Instantiate the RequestQueue.
	requestQueue = Volley.newRequestQueue(v.getContext());
	String url = "http://www.google.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) {
					// Display the first 500 characters of the response string.
					mTextView.setText("Response is: " + response.substring(0, 500));
				}
			}, new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			mTextView.setText("That didn't work!");
		}
	});

	stringRequest.setTag(TAG);
	// Add the request to the RequestQueue.
	requestQueue.add(stringRequest);
}
 
Example 21
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act__ss_ssl_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) {
            
            // Replace R.raw.test with your keystore 
            InputStream keyStore = getResources().openRawResource(R.raw.test);
            
            
            // 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_SsSslHttpClient.this,
                                     new ExtHttpClientStack(new SslHttpClient(keyStore, "test123", 44401)));

            StringRequest myReq = new StringRequest(Method.GET,
                                                    "https://ave.bolyartech.com:44401/https_test.html",
                                                    createMyReqSuccessListener(),
                                                    createMyReqErrorListener());

            queue.add(myReq);
        }
    });
}
 
Example 22
/**
 * Do a Volley String GET Request.
 *
 * @param endpoint
 *   The endpoint to query.
 */
public void doGetRequest(final String endpoint) {
    StringRequest getRequest = new StringRequest(Request.Method.GET, endpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    volleyRequestListener.OnSuccessRequest(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    volleyRequestListener.OnFailureRequest(error);
                }
            }
    )
    {
        @Override
        public Map<String, String> getHeaders() {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");

            String accessToken = user.getAccessToken();

            // Send empty access token in case the user is anonymous and the microsub endpoint
            // is still set to the Indigenous site.
            if (user.isAnonymous() && endpoint.contains(context.getString(R.string.anonymous_microsub_endpoint))) {
                accessToken = "";
            }

            headers.put("Authorization", "Bearer " + accessToken);
            return headers;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(context);
    queue.add(getRequest);
}
 
Example 23
/**
 * Do a Volley String POST Request.
 *
 * @param endpoint
 *   The endpoint to query.
 * @param params
 *   The params to send.
 */
public void doPostRequest(String endpoint, final Map<String, String> params) {
    StringRequest getRequest = new StringRequest(Request.Method.POST, endpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (volleyRequestListener != null) {
                        volleyRequestListener.OnSuccessRequest(response);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (volleyRequestListener != null) {
                        volleyRequestListener.OnFailureRequest(error);
                    }
                }
            }
    )
    {

        @Override
        protected Map<String, String> getParams() {
            return params;
        }

        @Override
        public Map<String, String> getHeaders() {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            headers.put("Authorization", "Bearer " + user.getAccessToken());
            return headers;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(context);
    queue.add(getRequest);
}
 
Example 24
Source Project: Place-Search-Service   Source File: PlaceSearchFragment.java    License: MIT License 5 votes vote down vote up
private void searchPlaces() {
        dialog.show();
        final StringBuffer buffer = new StringBuffer();
        buffer.append(BaseUrl.SEARCH_URL);
//        buffer.append("http://127.0.0.1:8080/");

        buffer.append("startLng=").append(Longitude);
        buffer.append("&");
        buffer.append("startLat=").append(Latitude);
        buffer.append("&");
        if (!TextUtils.isEmpty(mPlaceSearchDistance.getText())) {
            buffer.append("distance=").append(mPlaceSearchDistance.getText()).append("&");
        } else {
            buffer.append("distance=").append(10).append("&");
        }

        buffer.append("category=").append(formatted_category).append("&keyword=").append(mPlaceSearchKeyWord.getText());
        Log.v("request url",buffer.toString());

        RequestQueue mQueue = Volley.newRequestQueue(context);
        StringRequest request = new StringRequest(Request.Method.GET, buffer.toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                dialog.dismiss();
                PlacesSearchResultObj obj = new Gson().fromJson(response, PlacesSearchResultObj.class);
                Intent intent = new Intent(context, PlacesSearchResultActivtity.class);
                intent.putExtra("data", obj);
                intent.putExtra("url", buffer.toString());
                startActivity(intent);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dialog.dismiss();
                Toast.makeText(getContext(),"No network",Toast.LENGTH_LONG).show();
            }
        });
        mQueue.add(request);
    }
 
Example 25
Source Project: volley_demo   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void volley_post()
    {
        textview.setText("post String 开始了");
        // 错误url:String url = "ip.taobao.com/service/getIpInfo.php?ip=202.96.128.166"
        String url = "http://ip.taobao.com/service/getIpInfo.php?";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        textview.setText(response);
//                        Toast.makeText(MainActivity.this,response, Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
//                        Toast.makeText(MainActivity.this,error.toString(), Toast.LENGTH_SHORT).show();
                        textview.setText(error.toString());
                    }


                }
        ){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("ip", "202.96.128.166");
                return hashMap;
            }
        };

        requestTag = "volley_post";
        request.setTag(requestTag);
        MyApplication.getHttpQueues().add(request);
    }
 
Example 26
Source Project: volley   Source File: RequestQueueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void add_notifiesListener() throws Exception {
    RequestQueue.RequestEventListener listener = mock(RequestQueue.RequestEventListener.class);
    RequestQueue queue = new RequestQueue(new NoCache(), mMockNetwork, 0, mDelivery);
    queue.addRequestEventListener(listener);
    StringRequest req = mock(StringRequest.class);

    queue.add(req);

    verify(listener).onRequestEvent(req, RequestQueue.RequestEvent.REQUEST_QUEUED);
    verifyNoMoreInteractions(listener);
}
 
Example 27
Source Project: volley   Source File: RequestQueueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void finish_notifiesListener() throws Exception {
    RequestQueue.RequestEventListener listener = mock(RequestQueue.RequestEventListener.class);
    RequestQueue queue = new RequestQueue(new NoCache(), mMockNetwork, 0, mDelivery);
    queue.addRequestEventListener(listener);
    StringRequest req = mock(StringRequest.class);

    queue.finish(req);

    verify(listener).onRequestEvent(req, RequestQueue.RequestEvent.REQUEST_FINISHED);
    verifyNoMoreInteractions(listener);
}
 
Example 28
Source Project: volley_demo   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void volley_get()
    {
        textview.setText("get 开始了");
        // 错误url:String url = "ip.taobao.com/service/getIpInfo.php?ip=202.96.128.166"
        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=202.96.128.166";
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        textview.setText(response);
//                        Toast.makeText(MainActivity.this,response, Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
//                        Toast.makeText(MainActivity.this,error.toString(), Toast.LENGTH_SHORT).show();
                        textview.setText(error.toString());
                    }


                }
        );
        requestTag = "volley_get";
        request.setTag(requestTag);
        MyApplication.getHttpQueues().add(request);
    }
 
Example 29
Source Project: volley   Source File: RequestQueueTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void removeRequestEventListener_removesListener() throws Exception {
    StringRequest req = mock(StringRequest.class);
    RequestQueue.RequestEventListener listener = mock(RequestQueue.RequestEventListener.class);
    RequestQueue queue = new RequestQueue(new NoCache(), mMockNetwork, 0, mDelivery);
    queue.addRequestEventListener(listener);
    queue.removeRequestEventListener(listener);

    queue.sendRequestEvent(req, RequestQueue.RequestEvent.REQUEST_NETWORK_DISPATCH_STARTED);

    verifyNoMoreInteractions(listener);
}
 
Example 30
Source Project: volley   Source File: CacheDispatcherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);

    mRequest = new StringRequest(Request.Method.GET, "http://foo", null, null);
    mDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
}