/** * The default implementation of ImageListener which handles basic functionality * of showing a default image until the network response is received, at which point * it will switch to either the actual image or the error image. * @param view The imageView that the listener is associated with. * @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist. * @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist. */ public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) { return new ImageListener() { @Override public void onErrorResponse(VolleyError error) { if (errorImageResId != 0) { view.setImageResource(errorImageResId); } } @Override public void onResponse(ImageContainer response, boolean isImmediate) { if (response.getBitmap() != null) { view.setImageBitmap(response.getBitmap()); } else if (defaultImageResId != 0) { view.setImageResource(defaultImageResId); } } }; }
/** * 发送POST请求, 返回JSONObject对象数据 * @param url 请求地址 * @param listener 数据返回回调接口 * @param params POST请求参数 */ public void post(String url, final Fdv_CallBackListener<JSONObject> listener,Map<String,String> params){ JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if(listener!=null){ listener.onSuccessResponse(response); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(listener!=null){ listener.onErrorResponse(error); } } }); addRequest(jsonObjectRequest,params); }
/** * 普通文本等信息 Get请求 无参数,或者get请求的参数直接拼接在URL上面 * @param url 请求的地址 * @param listener 数据请求返回接口回调 */ public void get(String url, final Fdv_CallBackListener<String> listener){ StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { if(listener!=null){ listener.onSuccessResponse(response); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(listener!=null){ listener.onErrorResponse(error); } } }); addRequest(stringRequest); }
/** * The default implementation of ImageListener which handles basic functionality * of showing a default image until the network response is received, at which point * it will switch to either the actual image or the error image. * @param imageView The imageView that the listener is associated with. * @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist. * @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist. */ public static ImageListener getImageListener(final ImageView view, final int defaultImageResId, final int errorImageResId) { return new ImageListener() { @Override public void onErrorResponse(VolleyError error) { if (errorImageResId != 0) { view.setImageResource(errorImageResId); } } @Override public void onResponse(ImageContainer response, boolean isImmediate) { if (response.getBitmap() != null) { view.setImageBitmap(response.getBitmap()); } else if (defaultImageResId != 0) { view.setImageResource(defaultImageResId); } } }; }
@Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "onErrorResponse: " + error.toString()); findViewById(R.id.articleLoader).setVisibility(View.GONE); ConnectivityManager cm = (ConnectivityManager) getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting()) { // Display icon findViewById(R.id.noNetwork).setVisibility(View.VISIBLE); // Display permanent message Snackbar.make(findViewById(R.id.coordinatorArticle), getString(R.string.error_no_connection), Snackbar.LENGTH_INDEFINITE) .setAction(getString(R.string.error_no_connection_retry), new View.OnClickListener() { @Override public void onClick(View v) { REQUEST_QUEUE.add(new StringRequest(Request.Method.GET, shareLink, articleReceived, errorResponse)); } }).show(); } } }
private void requestJson() { RequestManager.addRequest(new StringRequest("http://shop.boohee" + ".com/store/pages/story_json", new Listener<String>() { public void onResponse(String response) { try { List<Story> stories = Story.parseStory(response); if (stories != null && stories.size() > 0) { WelcomeActivity.this.mDataList.clear(); WelcomeActivity.this.mDataList.addAll(stories); WelcomeActivity.this.mAdapter.notifyDataSetChanged(); stories.clear(); } } catch (Exception e) { e.printStackTrace(); } WelcomeActivity.this.setRefresh(false); } }, new ErrorListener() { public void onErrorResponse(VolleyError error) { Helper.showToast(error.toString()); WelcomeActivity.this.setRefresh(false); } }), this); setRefresh(true); }
public static void requestPosts(final onGetPosts callback){ RequestQueue queue = Volley.newRequestQueue(App.getAppContext()); StringRequest stringRequest = new StringRequest( Request.Method.GET, request.URL.LARAVEL_FEED_URL_LIVE, new Response.Listener<String>() { @Override public void onResponse(String response) { //finally return the posts list VolleyResponseHelper responseHelper = new VolleyResponseHelper(response); callback.onSuccess(responseHelper.getPosts()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(App.Tag,"error : "+VolleyErrorHelper.getMessage(error)); callback.onFailure(error); } } ); queue.add(stringRequest); }
void getPosts() { String url = getArguments().getString(ARG_SECTION_URL); url = getString(R.string.tumblr_api_url, url); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONObject meta = response.getJSONObject("meta"); if (meta.getInt("status") == 200) { JSONArray posts = response.getJSONObject("response").getJSONArray("posts"); adapter.setPosts(posts); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Activities", error.toString()); } }); VolleySingleton.getInstance(getContext()).addToRequestQueue(request); }
@Override public void getPosts(@NonNull final GetPostsCallback getPostsCallback) { GsonRequest<PostList> gsonRequest = new GsonRequest<>(mUrl, PostList.class, null, new Response.Listener<PostList>() { @Override public void onResponse(PostList list) { getPostsCallback.onPostsLoaded(list.posts); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { getPostsCallback.onPostsNotAvailable(volleyError.getMessage(), volleyError.getCause()); // + "\n" + volleyError.toString() } }); mRequestQueue.add(gsonRequest); }
public static String checkErrorType(VolleyError error) { String str = ""; if (error instanceof NoConnectionError) { str = ErrorCode.IS_NOT_NETWORK; } else if (error instanceof AuthFailureError) { str = ErrorCode.AUTH_FAILED; } else if (error instanceof TimeoutError) { str = ErrorCode.CONNECTION_TIMEOUT; } else if (error instanceof ParseError) { str = ErrorCode.PARSE_DATA_ERROR; } else if (error instanceof ServerError) { str = ErrorCode.SERVER_ERROR; } else if (error instanceof HttpError) { HttpError httpError = (HttpError) error; str = httpError.getMessage(); if (TextUtils.isEmpty(str)) { str = ErrorCode.REQUEST_ERROR; } } else { str = ErrorCode.REQUEST_ERROR; } return str; }
private static void requestGetMovies(String url, final GetMoviesCallback callback, Activity activity) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { callback.successGetMovies(MoviesMapping.getMoviesFromResponse(response)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.errorGetMovies(); } }); VolleyHelper.getInstance(activity).addToRequestQueue(request, activity); }
private String volleyGetJsonObjectRequest() { JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constant.JUHE_URL_GET, null, // 用post方式时,需更改为带请求参数的Object new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show(); } }); request.setTag(JSON_OBJECT_GET_TAG); MyApplication.getHttpQueues().add(request); return request.getTag().toString(); }
private static void setCountersDK(Context context) { JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, dkCountersURL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { dkUsersCount = response.get("users").toString(); dkProjectsCount = response.get("projects").toString(); dkTeamsCount = response.get("teams").toString(); dkLookupsCount = response.get("lookups").toString(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // log error? } }); RequestQueue requestQueue = Volley.newRequestQueue(context); requestQueue.add(jsonObjectRequest); }
private static void requestGetCredits(String url, final GetCastCallback callback, Activity activity) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { callback.successGetCast(MoviesMapping.getCast(response)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.errorGetCast(); } }); VolleyHelper.getInstance(activity).addToRequestQueue(request, activity); }
private void getActions(final DeviceDAO device) { Log.d(TAG, "TODO getActions"); String uri = Uri.parse(String.format("http://%s:%s/", device.getIP(), device.getPort())) .buildUpon().build().toString(); String credentials = device.getUsername() + ":" + device.getPassword(); byte[] t = credentials.getBytes(); byte[] auth = Base64.encode(t, Base64.DEFAULT); final String basicAuthValue = new String(auth); requestQueue.add(new StringRequest(Request.Method.POST, uri, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", "Basic " + basicAuthValue); params.put("Connection", "close"); return params; } }); }
protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight, ScaleType scaleType, final String cacheKey) { return new ImageRequest(requestUrl, new Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { onGetImageSuccess(cacheKey, response); } }, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { onGetImageError(cacheKey, error); } }); }
@Override protected void deliverResponse(String response) { if (isCanceled()) { return; } if (mResponse != null) { int statusCode = 0; Map<String, String> headers = null; String body = null; try { JSONObject responseJson = new JSONObject(response); if (!responseJson.isNull(RESPONSE_STATUS_CODE)) { statusCode = responseJson.getInt(RESPONSE_STATUS_CODE); } if (!responseJson.isNull(RESPONSE_HEADERS)) { headers = toMap(responseJson); } if (!responseJson.isNull(RESPONSE_BODY)) { body = responseJson.getString(RESPONSE_BODY); } if (statusCode < HttpStatus.SC_BAD_REQUEST) { mResponse.onSuccess(new AbstractResponse.Response(statusCode, headers, body)); } else { mResponse.onFailure(new AbstractResponse.Response(statusCode, headers, body)); } } catch (JSONException e) { e.printStackTrace(); mResponse.onError(new AbstractResponse.Response(statusCode, headers, new VolleyError(e))); } } }
public void moveCar(String method) { Log.i("testAdress", "start"); RequestQueue queue = Volley.newRequestQueue(getContext()); String url = API_URI + method; Log.i("url", url); // 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. int stringLength = response.length(); //testResult.setText("Response is: " + response.substring(0, stringLength - 1)); Log.i("Response", response.substring(0, stringLength - 1)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Response ERROR",error.toString()); //testResult.setText("That didn't work!"); error.printStackTrace(); } }); // Add the request to the RequestQueue. queue.add(stringRequest); }
protected void TransferRequest() { StringRequest stringgetfund = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/getmoney.php", new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equalsIgnoreCase("")) { LenderMoney = 0; } else { LenderMoney = Integer.parseInt(response); } GetBorrowerMoney(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(SelectedStatusActivity.this,error.toString(),Toast.LENGTH_SHORT).show(); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("id", LenderID); return params; }} ; requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringgetfund); }
private static void attemptRetryOnException(String logPrefix, Request<?> request, VolleyError exception) throws VolleyError { RetryPolicy retryPolicy = request.getRetryPolicy(); int oldTimeout = request.getTimeoutMs(); try { retryPolicy.retry(exception); } catch (VolleyError var6) { request.addMarker(String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout)); throw var6; } request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout)); }
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { if (mNumExceptionsToThrow > 0 || mNumExceptionsToThrow == ALWAYS_THROW_EXCEPTIONS) { if (mNumExceptionsToThrow != ALWAYS_THROW_EXCEPTIONS) { mNumExceptionsToThrow--; } throw new ServerError(); } requestHandled = request; return new NetworkResponse(mDataToReturn); }
@Override protected VolleyError parseNetworkError(VolleyError volleyError) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Volley failed to retrieve response", volleyError); } callback.onLoadFailed(volleyError); return super.parseNetworkError(volleyError); }
@Test public void testCallsLoadFailedIfStatusCodeIsNegativeOne() throws Exception { mockWebServer.enqueue(new MockResponse().setResponseCode(-1)); getFetcher().loadData(Priority.LOW, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
@Test public void testCallsLoadFailedAfterTooManyRedirects() throws Exception { for (int i = 0; i < 20; i++) { mockWebServer.enqueue(new MockResponse().setResponseCode(301) .setHeader("Location", mockWebServer.url("/redirect" + i).toString())); } getFetcher().loadData(Priority.NORMAL, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
@Test public void testCallsLoadFailedIfStatusCodeIs500() throws Exception { mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody("error")); getFetcher().loadData(Priority.NORMAL, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
@Test public void testCallsLoadFailedIfStatusCodeIs400() throws Exception { mockWebServer.enqueue(new MockResponse().setResponseCode(400).setBody("error")); getFetcher().loadData(Priority.LOW, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }
public void registerUser(final User user, final String deviceToken, final VolleyCallback callback) { Log.d(TAG, "registerUser: " + user); Log.d(TAG, "registerUser: " + deviceToken); StringRequest stringRequest = new StringRequest(Request.Method.POST, TTLEndpoints .URL_USER_REGISTER, new Response.Listener<String>() { @Override public void onResponse(String response) { callback.onSuccess(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onError(error.toString()); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> param = new HashMap<>(); param.put(NetworkKeys.KEY_USERNAME, user.getUsername()); param.put(NetworkKeys.KEY_EMAIL, user.getEmail()); param.put(NetworkKeys.KEY_PASSWORD, user.getPassword()); param.put(NetworkKeys.KEY_DEVICE_TOKEN, deviceToken); return param; } }; AppController.getInstance().addToRequestQueue(stringRequest, TAG); }
/** * 网络请求果壳的消息内容主体并存储 * @param id 对应的id */ private void startGuokrCache(final int id) { Cursor cursor = db.query("Guokr", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { if ((cursor.getInt(cursor.getColumnIndex("guokr_id")) == id) && (cursor.getString(cursor.getColumnIndex("guokr_content")).equals(""))) { StringRequest request = new StringRequest(Api.GUOKR_ARTICLE_LINK_V1 + id, new Response.Listener<String>() { @Override public void onResponse(String s) { ContentValues values = new ContentValues(); values.put("guokr_content", s); db.update("Guokr", values, "guokr_id = ?", new String[] {String.valueOf(id)}); values.clear(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } }); request.setTag(TAG); VolleySingleton.getVolleySingleton(CacheService.this).getRequestQueue().add(request); } } while (cursor.moveToNext()); } cursor.close(); }
protected void SendRequest() { SharedPreferences sharedPreferences = getSharedPreferences(UserPref.getSharedPrefName(), Context.MODE_PRIVATE); final String LenderType = sharedPreferences.getString(UserPref.getLendertypeSharedPref(),"Null"); StringRequest stringGetRequest = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/searchloansgrade.php", new Response.Listener<String>() { @Override public void onResponse(String response) { ParseJSON(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(LoanSearchActivity.this,error.toString(),Toast.LENGTH_SHORT).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put(UserPref.getlenderType(), LenderType); params.put(UserPref.getKeyGrade(), GradeStr); return params; }} ; requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringGetRequest); }
private void handleErrors(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { getView().showTimeOutError(); } else if (error instanceof ServerError) { getView().show500ServerError(); } else if (error instanceof NetworkError) { getView().showNetworkError(); } }
/** * Retorno da falha do RequestCustom * * @param error Informações da falha * @param msgError Mensagem do erro * @param statusCode Codigo de resposta */ @Override public void onError(VolleyError error, String msgError, int statusCode) { timeRequest(); print("StatusCode: " + statusCode); if (!settings.buildRelease) Log.e(TAG, "Error: " + msgError); PlainRequestQueue.getInstance().decRequestQueueSize(); System.gc(); settings.onResultRequest.onError(error, msgError, statusCode); }
/** * Attempts to prepare the request for a retry. If there are no more attempts remaining in the * request's retry policy, a timeout exception is thrown. * @param request The request to use. */ private static void attemptRetryOnException(String logPrefix, Request<?> request, VolleyError exception) throws VolleyError { RetryPolicy retryPolicy = request.getRetryPolicy(); int oldTimeout = request.getTimeoutMs(); try { retryPolicy.retry(exception); } catch (VolleyError e) { request.addMarker( String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout)); throw e; } request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout)); }
@Test public void shouldParseResponse() throws VolleyError { GeoLocationRequest request = new GeoLocationRequest(null, "", null, null); GeoLocationResult response = request.parseResponse(data.content); assertThat(response).isNotNull(); assertThat(response.getRegionName().equals("Tokyo")); }
protected void onGetImageError(String cacheKey, VolleyError error) { BatchedImageRequest request = (BatchedImageRequest) this.mInFlightRequests.remove(cacheKey); if (request != null) { request.setError(error); batchResponse(cacheKey, request); } }
/** * 用于更新XML文件的网络请求 */ public void andrUpdate(String returnedFileName,String returnedFileId){ RequestQueue requestQueue = MyApplication.getRequestQueue(); sharedPreferences = MyApplication.getSharedPreferences(); userId = sharedPreferences.getString("email",""); token = sharedPreferences.getString("token",""); JSONObject jsonObject = new JSONObject(); String fileName = dialogMsg+"_"+getWorkspaceSavePath(); try{ jsonObject.put("fileName",returnedFileName); jsonObject.put("fileString",AbstractBlocklyActivity.xmltostring);//AbstractBlocklyActivity.xmltostring jsonObject.put("fileId",returnedFileId);//这里应该通过一个方法来判断id的值,先暂时写成这样 jsonObject.put("userId",userId); jsonObject.put("token",token); }catch (JSONException e){ e.printStackTrace(); } Log.d("AndrUpdate_JsonObj",jsonObject.toString()); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url_upload, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { uploadReceive uploadReceive = new uploadReceive(); uploadReceive.setStatus(response.optString("status")); uploadReceive.setErrMsg(response.optString("errMsg")); Log.d("AndrUpdate_Response",response.toString()); judge_upload(uploadReceive.getStatus(),uploadReceive.getErrMsg()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("AndrUpdate_Error",error.toString(),error); } }); requestQueue.add(jsonObjectRequest); }
@Test public void testCallsLoadFailedIfRedirectLocationIsEmpty() throws Exception { for (int i = 0; i < 2; i++) { mockWebServer.enqueue(new MockResponse().setResponseCode(301)); } getFetcher().loadData(Priority.NORMAL, callback); waitForResponseLatch.await(); verify(callback).onLoadFailed(isA(VolleyError.class)); }