com.android.volley.Response Java Examples

The following examples show how to use com.android.volley.Response. 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: LeaderboardsFragment.java    From android-kubernetes-blockchain with Apache License 2.0 6 votes vote down vote up
public void getStatus(final int position) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, BACKEND_URL + "/registerees/totalUsers" , null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        int totalUsers = response.getInt("count");
                        status.setText(String.format("You are position %d of %d", position, totalUsers));
                        totalNumberOfUsers = totalUsers;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "That didn't work!");
        }
    });
    queue.add(jsonObjectRequest);
}
 
Example #2
Source File: Request.java    From RestaurantApp with GNU General Public License v3.0 6 votes vote down vote up
public void requestVolleyDeskList(final ChangeDeskStatus changeDeskStatus, final int orderId, final int status){

        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestMethod, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                changeDeskStatus.changeStatus(response);
            }
        }, 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, Integer> params = new HashMap<String, Integer>();
                params.put("orderId", orderId);
                params.put("status", status);
                return new JSONObject(params).toString().getBytes();
            }
        };

        requestQueue.add(jsonObjectRequest);

    }
 
Example #3
Source File: AboutModelImpl.java    From allenglish with Apache License 2.0 6 votes vote down vote up
@Override
public void checkNewVersion() {
    Map<String, String> map = new HashMap<>();
    map.put("appKey", "56bd51ddb76877188a1836d791ed8436");
    map.put("_api_key", "a08ef5ee127a27bd4210f7e1f9e7c84e");
    VolleySingleton.getInstance().addToRequestQueue(new GsonRequest<>(Request.Method.POST, "https://www.pgyer.com/apiv2/app/view",
            ViewBean.class,
            null, map,
            new Response.Listener<ViewBean>() {
                @Override
                public void onResponse(ViewBean response) {
                    if (response.data.buildVersion.equals(CommonUtils.getVersionName(BaseApplication.getInstance()))) {
                        listener.onNoNewVersion();
                    } else {
                        listener.onGetANewVersion(response.data.buildUpdateDescription);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onCheckFailed();
        }
    }));
}
 
Example #4
Source File: searchableactivity.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
private void sendjsonRequest(){

        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET,"http://brunoferreira.esy.es/serverdata.php",null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                casas=parsejsonResponse(response);
                adaptador.setCasas(casas);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Snackbar.make(rvc1,"Falha ao ligar ao servidor",Snackbar.LENGTH_LONG).show();

            }
        });

        requestQueue.add(jsonArrayRequest);
    }
 
Example #5
Source File: NetRequestUtil.java    From TouchNews with Apache License 2.0 6 votes vote down vote up
/**
 * get请求获取JsonObject
 *
 * @param url      url
 * @param param    param
 * @param listener callback
 */
public void getJson(String url, Map<String, String> param, final RequestListener listener) {
    url += prepareParam(param);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            listener.onResponse(response);
            Log.i(TAG, response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onError(error);
            Log.i(TAG, error.getMessage(), error);
        }
    });
    mRequestQueue.add(jsonObjectRequest);
}
 
Example #6
Source File: BaseLearningModelImpl.java    From allenglish with Apache License 2.0 6 votes vote down vote up
@Override
public void getLeanCloudBean(String tableName, int limit, int skin, String tag, String createdAt) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.CONTENT_TYPE, Constants.CONTENT_TYPE_VALUE);
    headers.put(Constants.X_LC_Id, Constants.X_LC_ID_VALUE);
    long timestamp = System.currentTimeMillis();
    headers.put(Constants.X_LC_SIGN, MD5.md5(timestamp + Constants.X_LC_KEY_VALUE) + "," + timestamp);
    String url;
    if (tag != null) {
        url = "https://leancloud.cn:443/1.1/classes/" + tableName + "?where={\"createdAt\":{\"$lt\":{\"__type\":\"Date\",\"iso\":\"" + createdAt + "\"}},\"tag\":\"" + StringUtils.encodeText(tag) + "\"}&limit=" + limit + "&order=-createdAt";
    } else {
        url = "https://leancloud.cn:443/1.1/classes/" + tableName + "?where={\"createdAt\":{\"$lt\":{\"__type\":\"Date\",\"iso\":\"" + createdAt + "\"}}}&limit=" + limit + "&order=-createdAt";
    }
    VolleySingleton.getInstance()
            .addToRequestQueue(new GsonRequest<>(url, LeanCloudApiBean.class, headers, null, new Response.Listener<LeanCloudApiBean>() {
                @Override
                public void onResponse(LeanCloudApiBean response) {
                    beanList.addAll(response.results);
                    addListAds();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }));
}
 
Example #7
Source File: VolleyProcessor.java    From HttpRequestProcessor with 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 #8
Source File: LastFMProvider.java    From odyssey with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetches the image URL for the raw image blob.
 *
 * @param model         Album to look for an image
 * @param listener      Callback listener to handle the response
 * @param errorListener Callback to handle a fetch error
 */
private void getAlbumImageURL(final ArtworkRequestModel model,
                              final Response.Listener<JSONObject> listener, final Response.ErrorListener errorListener) {
    String albumName = model.getEncodedAlbumName();
    String artistName = model.getEncodedArtistName();

    if (albumName.isEmpty() || artistName.isEmpty()) {
        errorListener.onErrorResponse(new VolleyError("required arguments are empty"));
    } else {
        String url = LAST_FM_API_URL + "album.getinfo&album=" + albumName + "&artist=" + artistName + "&api_key=" + API_KEY + LAST_FM_FORMAT_JSON;

        if (BuildConfig.DEBUG) {
            Log.v(TAG, url);
        }

        OdysseyJsonObjectRequest jsonObjectRequest = new OdysseyJsonObjectRequest(url, null, listener, errorListener);

        mRequestQueue.add(jsonObjectRequest);
    }
}
 
Example #9
Source File: AccountFragment.java    From openshop.io-android with MIT License 6 votes vote down vote up
private void syncUserData(@NonNull User user) {
    String url = String.format(EndPoints.USER_SINGLE, SettingsMy.getActualNonNullShop(getActivity()).getId(), user.getId());
    pDialog.show();

    GsonRequest<User> getUser = new GsonRequest<>(Request.Method.GET, url, null, User.class,
            new Response.Listener<User>() {
                @Override
                public void onResponse(@NonNull User response) {
                    Timber.d("response: %s", response.toString());
                    SettingsMy.setActiveUser(response);
                    refreshScreen(SettingsMy.getActiveUser());
                    if (pDialog != null) pDialog.cancel();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (pDialog != null) pDialog.cancel();
            MsgUtils.logAndShowErrorMessage(getActivity(), error);
        }
    }, getFragmentManager(), user.getAccessToken());
    getUser.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    getUser.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(getUser, CONST.ACCOUNT_REQUESTS_TAG);
}
 
Example #10
Source File: NetworkUtil.java    From UberClone with MIT License 6 votes vote down vote up
public void httpRequest(String url, final HttpResponse httpResponse){
    if(availableNetwok()){
        RequestQueue queue= Volley.newRequestQueue(context);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        httpResponse.httpResponseSuccess(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(stringRequest);
    }
}
 
Example #11
Source File: ImageRequest.java    From volley with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #12
Source File: separadorporto.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
private void sendjsonRequest(){

        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET,"http://brunoferreira.esy.es/serverdata.php",null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                casas=parsejsonResponse(response);
                adaptador.setCasas(casas);
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setVisibility(View.VISIBLE);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setVisibility(View.VISIBLE);
                Snackbar.make(recyclerViewtodas,"Falha ao ligar ao servidor",Snackbar.LENGTH_LONG).show();

            }
        });

        requestQueue.add(jsonArrayRequest);
    }
 
Example #13
Source File: UpdateCartItemDialogFragment.java    From openshop.io-android with MIT License 6 votes vote down vote up
private void getProductDetail(CartProductItem cartProductItem) {
    String url = String.format(EndPoints.PRODUCTS_SINGLE, SettingsMy.getActualNonNullShop(getActivity()).getId(), cartProductItem.getVariant().getProductId());

    setProgressActive(true);

    GsonRequest<Product> getProductRequest = new GsonRequest<>(Request.Method.GET, url, null, Product.class,
            new Response.Listener<Product>() {
                @Override
                public void onResponse(@NonNull Product response) {
                    setProgressActive(false);
                    setSpinners(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            setProgressActive(false);
            MsgUtils.logAndShowErrorMessage(getActivity(), error);
        }
    });
    getProductRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    getProductRequest.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(getProductRequest, CONST.UPDATE_CART_ITEM_REQUESTS_TAG);
}
 
Example #14
Source File: ProductFragment.java    From openshop.io-android with MIT License 6 votes vote down vote up
/**
 * Load product wishlist info. Determine state of wishlist button.
 * If a user is logged out, nothing will happen.
 *
 * @param productId id of product.
 */
private void getWishListInfo(long productId) {
    User user = SettingsMy.getActiveUser();
    if (user != null) {
        // determine if product is in wishlist
        String wishlistUrl = String.format(EndPoints.WISHLIST_IS_IN_WISHLIST, SettingsMy.getActualNonNullShop(getActivity()).getId(), productId);
        JsonRequest getWishlistInfo = new JsonRequest(Request.Method.GET, wishlistUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                prepareWishListButton(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MsgUtils.logAndShowErrorMessage(getActivity(), error);
            }
        }, getFragmentManager(), user.getAccessToken());
        getWishlistInfo.setRetryPolicy(MyApplication.getDefaultRetryPolice());
        getWishlistInfo.setShouldCache(false);
        MyApplication.getInstance().addToRequestQueue(getWishlistInfo, CONST.PRODUCT_REQUESTS_TAG);
    }
}
 
Example #15
Source File: ShipfForMeService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserDeleteShipForMeOrder(final int orderId, final Listener<Void> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(),
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {if (listener != null) {
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            final ArrayList<Object> params = new ArrayList<>();
            params.add(orderId);

            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id", getMsgID());
            msg.put("method", "ShipfForMe.UserDeleteShipForMeOrder");
            msg.put("params", params);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example #16
Source File: PaymentService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserDoCreditCardTopUp(final double total, final double creditCardFee, final ArrayList<String> paymentIds, final String telephone, final Listener<String> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Payment/UserDoCreditCardTopUp",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    String result;
                    result = BaseModule.doFromJSON(response, String.class);

                    listener.onResponse(result);
                } catch (Exception ex) {
                     
                    // Log.d("ex", ex.toString());
                    // Log.d("jsonObject", response);
                     
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            HashMap<String, Object> msg = new HashMap<String, Object>();
            msg.put("total", total);
            msg.put("creditCardFee", creditCardFee);
            msg.put("paymentIds", paymentIds);
            msg.put("telephone", telephone);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example #17
Source File: UserInfoActivity.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
private void readNetBuffer() {
    StringRequest getUserInfo = new PowerStringRequest(Request.Method.POST,
            NONoConfig.makeNONoSonURL("/quickask_get_userinfo_home.php"),
            new PowerListener() {
                @Override
                public void onCorrectResponse(String s) {
                    super.onCorrectResponse(s);
                    try{
                        userInfo =  new Gson().fromJson(s,new TypeToken<UserInfo>(){}.getType());
                    }catch(Exception e){
                        Toast.makeText(UserInfoActivity.this,"获取用户信息错误(等级:严重),请联系开发者!",Toast.LENGTH_SHORT).show();
                    }

                    UpdateUI(userInfo);
                }

                @Override
                public void onJSONStringParseError() {
                    super.onJSONStringParseError();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String,String> params = new HashMap<>();
            params.put("me_id",MyApp.userInfo.userId);
            params.put("user_id",String.valueOf(userInfo.data.user_id));

            return params;
        }
    };
    MyApp.getInstance().volleyRequestQueue.add(getUserInfo);
}
 
Example #18
Source File: PutRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
public PutRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  super(Method.PUT, url, errorListener);
  mListener = listener;
  this.entity = entity;
  this.contentType = contentType;
  this.apiHeaders = apiHeaders;
}
 
Example #19
Source File: ShipfForMeService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserUpdateShipForMeOrder(final int orderId, final String warehouseCode, final String shipperName, final String wayBill, final String alternative, final boolean takePhoto, final String repack, final Listener<Void> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "ShipfForMe/UserUpdateShipForMeOrder",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {if (listener != null) {
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            HashMap<String, Object> msg = new HashMap<String, Object>();
            msg.put("orderId", orderId);
            msg.put("warehouseCode", warehouseCode);
            msg.put("shipperName", shipperName);
            msg.put("wayBill", wayBill);
            msg.put("alternative", alternative);
            msg.put("takePhoto", takePhoto);
            msg.put("repack", repack);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example #20
Source File: DeleteRequest.java    From swagger-aem with Apache License 2.0 5 votes vote down vote up
public DeleteRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  super(Method.DELETE, url, errorListener);
  mListener = listener;
  this.entity = entity;
  this.contentType = contentType;
  this.apiHeaders = apiHeaders;
}
 
Example #21
Source File: MainActivity.java    From custom-auth-samples with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param kakaoAccessToken Access token retrieved after successful Kakao Login
 * @return Task object that will call validation server and retrieve firebase token
 */
private Task<String> getFirebaseJwt(final String kakaoAccessToken) {
    final TaskCompletionSource<String> source = new TaskCompletionSource<>();

    RequestQueue queue = Volley.newRequestQueue(this);
    String url = getResources().getString(R.string.validation_server_domain) + "/verifyToken";
    HashMap<String, String> validationObject = new HashMap<>();
    validationObject.put("token", kakaoAccessToken);

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(validationObject), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                String firebaseToken = response.getString("firebase_token");
                source.setResult(firebaseToken);
            } catch (Exception e) {
                source.setException(e);
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, error.toString());
            source.setException(error);
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("token", kakaoAccessToken);
            return params;
        }
    };

    queue.add(request);
    return source.getTask();
}
 
Example #22
Source File: GsonRequest.java    From android-network-security-config with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: ApiInvoker.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
  try {
    Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener);
    if (request != null) {
      mRequestQueue.add(request);
    }
  } catch (UnsupportedEncodingException ex) {
    throw new ApiException(0, "UnsupportedEncodingException");
  }
}
 
Example #24
Source File: PostRequest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #25
Source File: UpdateRequest.java    From MagicPrint-ECommerce-App-Android with MIT License 5 votes vote down vote up
public UpdateRequest(String name, String mobile, String email, String newemail, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_URL, listener, null);
    parameters = new HashMap<>();
    parameters.put("name", name);
    parameters.put("newemail", newemail);
    parameters.put("mobile", mobile);
    parameters.put("email", email);

}
 
Example #26
Source File: NetRequestUtil.java    From TouchNews with Apache License 2.0 5 votes vote down vote up
/**
     * get请求获取JsonObject 带Headers参数
     *
     * @param url      url
     * @param param    param
     * @param listener callback
     */
    public void getJsonWithHeaders(String url, final Map<String, String> param, final Map<String, String> headers, final RequestListener listener) {
        url += prepareParam(param);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
//                                Log.i ( TAG, response.toString ( ) );
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error);
//                                Log.i ( TAG, error.getMessage ( ), error );
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers == null) {
                    return super.getHeaders();
                } else {
                    return headers;
                }

            }

        };
        mRequestQueue.add(jsonObjectRequest);

    }
 
Example #27
Source File: KCommands.java    From kboard with GNU General Public License v3.0 5 votes vote down vote up
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 #28
Source File: StringRequest.java    From volley with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("DefaultCharset")
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        // Since minSdkVersion = 8, we can't call
        // new String(response.data, Charset.defaultCharset())
        // So suppress the warning instead.
        parsed = new String(response.data);
    }
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #29
Source File: PutRequest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #30
Source File: PaymentService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest GetTopUpDescription(final Listener<ArrayList<String>> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Payment/GetTopUpDescription",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    ArrayList<String> result;
                    result = BaseModule.doFromJSONArray(response, String.class);

                    listener.onResponse(result);
                } catch (Exception ex) {
                     
                    // Log.d("ex", ex.toString());
                    // Log.d("jsonObject", response);
                     
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            return "".getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}