@Test public void publicMethods() throws Exception { // Catch-all test to find API-breaking changes. assertNotNull(Response.class.getMethod("success", Object.class, Cache.Entry.class)); assertNotNull(Response.class.getMethod("error", VolleyError.class)); assertNotNull(Response.class.getMethod("isSuccess")); assertNotNull(Response.Listener.class.getDeclaredMethod("onResponse", Object.class)); assertNotNull(Response.ErrorListener.class.getDeclaredMethod("onErrorResponse", VolleyError.class)); assertNotNull(NetworkResponse.class.getConstructor(int.class, byte[].class, Map.class, boolean.class, long.class)); assertNotNull(NetworkResponse.class.getConstructor(int.class, byte[].class, Map.class, boolean.class)); assertNotNull(NetworkResponse.class.getConstructor(byte[].class)); assertNotNull(NetworkResponse.class.getConstructor(byte[].class, Map.class)); }
/** * 请求返回JSONObject对象 Get请求 无参数,或者get请求的参数直接拼接在URL上面 * @param url 请求地址 * @param listener 数据回调接口 */ public void get(String url, final Fdv_CallBackListener<JSONObject> listener){ JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, 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); }
/** * 普通文本等信息 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); }
/** * 根据地址和请求参数 发送POST请求 * @param url 地址服务器地址 * @param listener 数据加载回调接口 * @param params 请求参数 */ public void post(String url, final Fdv_CallBackListener<String> listener,Map<String,String> params){ StringRequest stringRequest=new StringRequest(Request.Method.POST, 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,params); }
/** * 缓存 */ private void requestOkHttp() { new OkHttpClient.Builder().addInterceptor(new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { okhttp3.Request request = chain.request(); // chain.request().newBuilder().addHeader().build() okhttp3.Response response = chain.proceed(request); return response; } }).cache(new okhttp3.Cache(getCacheDir(), 5 * 1024 * 1024)).build(); okhttp3.Request request_forceNocache = new okhttp3.Request.Builder().cacheControl(new CacheControl.Builder().noCache().build()).url("").build(); okhttp3.Request request_forceCache = new okhttp3.Request.Builder().cacheControl(new CacheControl.Builder().maxAge(0, TimeUnit.SECONDS).build()).url("").build(); }
private Response.Listener leaveChatSuccess() { return new Response.Listener() { @Override public void onResponse(Object response) { AppController controller = AppController.getInstance(); Chat bo = controller.getCurrentActiveChat(); controller.removeChat(bo.getChatId(), controller.getCurrentActiveChatType()); finish(); // Reset current active chat. controller.setCurrentActiveChat(bo.getChatType(), null); // Show find connection after leaving a chat room. startActivity(new Intent(getApplicationContext(), FindConnectionActivity.class)); } }; }
private static void requestGetMovie(String url, final GetMovieCallback callback, Activity activity) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { callback.successGetMovie(MoviesMapping.getMovieFromJson(response)); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.errorGetMovie(); } }); VolleyHelper.getInstance(activity).addToRequestQueue(request, activity); }
public void requestVolleyAuth(final VolleyCallback callback, final String username, final String password){ final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestMethod, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { callback.onSuccesAuth(response); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, String.valueOf(error), Toast.LENGTH_SHORT).show(); } }){ @Override public byte[] getBody() { HashMap<String, String> params = new HashMap<String, String>(); params.put("username", username); params.put("password", password); return new JSONObject(params).toString().getBytes(); } }; requestQueue.add(jsonObjectRequest); }
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 void requestOkHttpGet() { new Thread(new Runnable() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void run() { if (okHttpClient == null) { okHttpClient = new OkHttpClient(); } okhttp3.Request.Builder builder = new okhttp3.Request.Builder(); okhttp3.Request request = builder.url("http://www.google.com").build(); //必须在这定义 try (okhttp3.Response response = okHttpClient.newCall(request).execute()) { String s = response.body().string();//注意这里是string()不是toString(); Log.i(TAG, "requestOkHttpGet: " + s); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
private void loadLocationFromApi() { if (subscriptionKey == null) { Log.d(TAG, "Cannot read metadata `com.rakuten.tech.mobile.perf.SubscriptionKey` from " + "manifest automated performance tracking will not work."); } new GeoLocationRequest(urlPrefix, subscriptionKey, new Response.Listener<GeoLocationResult>() { @Override public void onResponse(GeoLocationResult newLocation) { LocationData locationData = new LocationData(newLocation.getCountryName(), newLocation.getRegionName()); writeLocationToCache(locationData); getObservable().publish(locationData); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, "Error loading location", error); } }).queue(requestQueue); }
@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); }
public static void sendStartEvent(String installationID) { // Prepare parameters Map<String, String> map = new HashMap<>(); map.put("installation_id", installationID); map.put("school", SAConfig.schoolIdentifier); map.put("client_version", BuildConfig.VERSION_NAME); map.put("device_info", SAUtils.getDeviceModel()); JSONObject params = new JSONObject(map); // Make request JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, baseURL + "/start", params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) {} }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) {} }); SAGlobal.sharedRequestQueue.add(jsonObjectRequest); }
@Override protected Response<RemoteResponse> parseNetworkResponse(NetworkResponse response) { RemoteResponse remoteResponse = new RemoteResponse(); if (null != response) { try { remoteResponse.setStatusCode(response.statusCode); remoteResponse.setResponseMessage(HttpStatusNoteMap.getNote(response.statusCode)); remoteResponse.setInterval(response.networkTimeMs); remoteResponse.setHeaders(response.headers); String str = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8")); remoteResponse.setResponse(str); } catch (UnsupportedEncodingException e) { remoteResponse.setResponse(e.getMessage()); } } else { remoteResponse.setStatusCode(-1); remoteResponse.setResponseMessage("Error"); } return Response.success(remoteResponse, HttpHeaderParser.parseCacheHeaders(response)); }
public void requestServer(final String url) { queue.add(new StringRequest(Request.Method.GET, url+"/ping", new Response.Listener<String>() { @Override public void onResponse(String response) { sharedPref = context.getSharedPreferences( "preference_file", Context.MODE_PRIVATE); boolean dataLoaded = sharedPref.getBoolean("IsDataLoaded", false); if (!dataLoaded){ downloadFiles(url); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } })); }
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); }
protected Response<String> parseNetworkResponse(NetworkResponse response) { if (response == null) { return null; } String parsed; try { parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } catch (Exception e) { parsed = new String(response.data); } return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); }
@Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
public Bitmap getUserFaceBitmap(String userId, final UserListCallback callback) { final String GET_USER_FACE_URL = "http://" + Config.RECOGNITION_SERVER_IP + ":" + Config.RECOGNITION_SERVER_PORT + "/face?userid=" + userId; Response.Listener<JSONObject> rightListener = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject object) { try { int ret = object.getInt("Ret"); String strFace = object.optString("Image"); if (ret == 0) { //将base64的String 转换为合适大小的Bitmap userFace = ImageUtils.decodeBase64ToBitmap(strFace); callback.onBitmapReady(userFace); } } catch (JSONException e) { e.printStackTrace(); } } }; Response.ErrorListener errorListener = new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError volleyError) { Log.i(TAG, "getUserFaceBitmap()--Error:"+volleyError.getMessage()); } }; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.GET, GET_USER_FACE_URL, null, rightListener, errorListener); VolleySingleton.getVolleySingleton(context).addToRequestQueue(jsonObjectRequest); return userFace; }
/** * For API compatibility with the pre-ScaleType variant of the constructor. Equivalent to * the normal constructor with {@code ScaleType.CENTER_INSIDE}. */ @Deprecated public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight, Config decodeConfig, Response.ErrorListener errorListener) { this(url, listener, maxWidth, maxHeight, ScaleType.CENTER_INSIDE, decodeConfig, errorListener); }
protected void UpdateLenderMoney() { StringRequest stringgetfund = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/setaccountmoney.php", new Response.Listener<String>() { @Override public void onResponse(String response) { UpdateBorrowerMoney(); } }, 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); params.put("money", Integer.toString( LenderMoney)); return params; }} ; requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringgetfund); }
@Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } }
private void getBooks() { //GET request to fetch books JsonArrayRequest booksRequest = new JsonArrayRequest(Request.Method.GET, Helper.GET_BOOKS_URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Toast.makeText(ListAllBookActivity.this, "List is loading..", Toast.LENGTH_SHORT).show(); for(int i=0;i<response.length();i++){ try { JSONObject object = response.getJSONObject(i); String bookImage = object.getString("image"); String bookTitle = object.getString("title"); String bookPrice = object.getString("amazonPrice"); int userPrice = object.getInt("userPrice"); String author = object.getString("author"); Book b = new Book(bookTitle,author,bookImage,bookPrice,userPrice); bookList.add(b); } catch (JSONException e) { e.printStackTrace(); } } Log.d("books_size",bookList.size()+" "); bookListAdapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); AppController.getInstance().addToRequestQueue(booksRequest); }
@Test public void specifiedCharsetJsonObject() throws Exception { byte[] data = jsonObjectString().getBytes(Charset.forName("ISO-8859-1")); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json; charset=iso-8859-1"); NetworkResponse network = new NetworkResponse(data, headers); JsonObjectRequest objectRequest = new JsonObjectRequest("", null, null, null); Response<JSONObject> objectResponse = objectRequest.parseNetworkResponse(network); assertNotNull(objectResponse); assertTrue(objectResponse.isSuccess()); //don't check the text in Czech, ISO-8859-1 doesn't support some Czech characters assertEquals(COPY_VALUE, objectResponse.result.getString(COPY_NAME)); }
void makeJSONObjectRequest(){ JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.GET, new RequestBuilder().addIngredients("onions", "garlic").setQueryParam("pizza").build(), null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { //Get the json array from results JSONArray resultsArray = response.getJSONArray("results"); List<Recipe> recipeList = Recipe.recipesForJSONArray(resultsArray); ((RecipeListFragment) getFragmentManager().findFragmentById(R.id.recipeFragment)) .updateData(recipeList); //responseText.setText(recipeList.get(0).title); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { responseText.setText("Something went wrong!"); } } ); queue.add(jsonObjectRequest); }
/** * 网络请求果壳的消息内容主体并存储 * @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() { StringRequest stringGetRequest = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/statusloans.php", new Response.Listener<String>() { @Override public void onResponse(String response) { ParseJSON(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(LoanStatusActivity.this,error.toString(),Toast.LENGTH_SHORT).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("id", ID); return params; }} ; requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringGetRequest); }
public LoginDetailsCheck(String email , String fname , String lname , Response.Listener<String> listener){ super(Method.POST, FirstEntry_url , listener, null); params= new HashMap<>(); params.put("email",email); params.put("fname",fname); params.put("lname",lname); }
private Response.Listener<JSONObject> loadTravelerIdSuccess() { return new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { travelerId = response.getInt("id"); currentUser = new Traveler( response.getInt("id"), response.getString("firstName"), response.getString("lastName"), response.getString("email"), response.getString("uid") ); // Make the current user for other activities available. AppController.getInstance().setCurrentUser(currentUser); // Load the private chats of this user. AppController.getInstance().addToRequestQueue(new JsonArrayRequest(Request.Method.GET, "http://trvlr.ch:8080/api/private-chats/list/" + currentUser.getId(), null, loadTravelerChatsSuccess(AppController.CHATROOM_TYPE_PRIVATE), loadError() )); // Load the public chats of this user. AppController.getInstance().addToRequestQueue(new JsonArrayRequest(Request.Method.GET, "http://trvlr.ch:8080/api/public-chats/list/" + currentUser.getId(), null, loadTravelerChatsSuccess(AppController.CHATROOM_TYPE_PUBLIC), loadError() )); } catch (JSONException e) { Toast.makeText(BaseDrawerActivity.this, TAG + ": " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }; }
/** * Make a GET request and return a parsed object from JSON. * * @param url URL of the request to make * @param clazz Relevant class object, for Gson's reflection * @param headers Map of request headers */ public GsonRequest(String url, Class<T> clazz, Map<String, String> headers, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(Method.GET, url, errorListener); this.clazz = clazz; this.headers = headers; this.listener = listener; }
protected void UpdateLenderMoney() { StringRequest stringgetfund = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/setaccountmoney.php", new Response.Listener<String>() { @Override public void onResponse(String response) { UpdateBorrowerMoney(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(SelectedLoanActivity.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); params.put("money", Integer.toString( LenderMoney)); return params; }} ; requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringgetfund); }
/** * Creates a new request. * * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param jsonRequest What to post with the request * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ public JsonStringRequest( final int method, final String url, final String jsonRequest, final Response.Listener<String> listener, final Response.ErrorListener errorListener ) { super(method, url, jsonRequest, listener, errorListener); }
private void verifyResize(NetworkResponse networkResponse, int maxWidth, int maxHeight, int expectedWidth, int expectedHeight) { ImageRequest request = new ImageRequest( "", null, maxWidth, maxHeight, Config.RGB_565, null); Response<Bitmap> response = request.parseNetworkResponse(networkResponse); assertNotNull(response); assertTrue(response.isSuccess()); Bitmap bitmap = response.result; assertNotNull(bitmap); assertEquals(expectedWidth, bitmap.getWidth()); assertEquals(expectedHeight, bitmap.getHeight()); }
@Test public void specifiedCharsetJsonArray() throws Exception { byte[] data = jsonArrayString().getBytes(Charset.forName("ISO-8859-2")); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json; charset=iso-8859-2"); NetworkResponse network = new NetworkResponse(data, headers); JsonArrayRequest arrayRequest = new JsonArrayRequest("", null, null); Response<JSONArray> arrayResponse = arrayRequest.parseNetworkResponse(network); assertNotNull(arrayResponse); assertTrue(arrayResponse.isSuccess()); assertEquals(TEXT_VALUE, arrayResponse.result.getString(TEXT_INDEX)); // don't check the copyright symbol, ISO-8859-2 doesn't have it, but it has Czech characters }
@Test public void publicMethods() throws Exception { // Catch-all test to find API-breaking changes. assertNotNull(StringRequest.class.getConstructor(String.class, Response.Listener.class, Response.ErrorListener.class)); assertNotNull(StringRequest.class.getConstructor(int.class, String.class, Response.Listener.class, Response.ErrorListener.class)); }
private void verifyResize(NetworkResponse networkResponse, int maxWidth, int maxHeight, ScaleType scaleType, int expectedWidth, int expectedHeight) { ImageRequest request = new ImageRequest("", null, maxWidth, maxHeight, scaleType, Config.RGB_565, null); Response<Bitmap> response = request.parseNetworkResponse(networkResponse); assertNotNull(response); assertTrue(response.isSuccess()); Bitmap bitmap = response.result; assertNotNull(bitmap); assertEquals(expectedWidth, bitmap.getWidth()); assertEquals(expectedHeight, bitmap.getHeight()); }