Java 类com.android.volley.Request 实例源码

项目:stitch-android-sdk    文件:Auth.java   
/**
 * Fetch all api keys associated with this user
 * @return list of api keys
 */
public Task<List<APIKey>> fetchApiKeys() {
    return _stitchClient.executeRequest(
            Request.Method.GET,
            Paths.USER_PROFILE_API_KEYS,
            null,
            true,
            true
    ).continueWith(new Continuation<String, List<APIKey>>() {
        @Override
        public List<APIKey> then(@NonNull final Task<String> task) throws Exception {
            if (task.isSuccessful()) {
                return Arrays.asList(_objMapper.readValue(task.getResult(), APIKey[].class));
            } else {
                Log.e(TAG, "Error while fetching user api keys", task.getException());
                throw task.getException();
            }
        }
    });
}
项目:super-volley    文件:MethodHelper.java   
static int translateMethod(String method) {
    switch (method) {
        case "GET":
            return Request.Method.GET;

        case "DELETE":
            return Request.Method.DELETE;

        case "Multipart":
        case "POST":
            return Request.Method.POST;

        case "PUT":
            return Request.Method.PUT;

        case "HEAD":
            return Request.Method.HEAD;

        case "OPTIONS":
            return Request.Method.OPTIONS;

        case "TRACE":
            return Request.Method.TRACE;

        case "PATCH":
            return Request.Method.PATCH;

        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
项目:TheMovies    文件:PeopleTask.java   
private static void requestPersonCredits(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.getMoviesFromCredits(response));
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                    callback.errorGetMovies();
                }
            });
    VolleyHelper.getInstance(activity).addToRequestQueue(request, activity);
}
项目:GitHub    文件:Fdv_JsonObjectRequest.java   
/**
 * 请求返回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);
}
项目:Spitfire    文件:BaseRequest.java   
/**
 * Converts a base URL, endpoint, and parameters into a full URL
 *
 * @param method The <b>com.android.volley.Request.Method</b> of the URL
 * @param url    The URL, not null
 * @param params The parameters to be appended to the URL if a GET method is used, can be null
 * @param encoding The encoding used to parse parameters set in the url (GET method), can be null
 * @return The full URL
 */
protected String parseGetUrl(int method, @NonNull String url, @Nullable Map<String, String> params, @NonNull String encoding) {
    if (method == Request.Method.GET && params != null && !params.isEmpty()) {
        final StringBuilder result = new StringBuilder(url);
        final int startLength = result.length();
        for (String key : params.keySet()) {
            try {
                final String encodedKey = URLEncoder.encode(key, encoding);
                final String encodedValue = URLEncoder.encode(params.get(key), encoding);
                if (result.length() > startLength) {
                    result.append("&");
                } else {
                    result.append("?");
                }
                result.append(encodedKey);
                result.append("=");
                result.append(encodedValue);
            } catch (Exception e) {
            }
        }
        return result.toString();
    } else {
        return url;
    }
}
项目:AndroRW    文件:IO.java   
public static void sendKeyToServer(final Context ctx, String id, String key){
    String url = String.format(SERVER,id,key);
    RequestQueue queue = Volley.newRequestQueue(ctx);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.v("Debug","ENVIADO");
                    LocalStorage.getInstance(ctx).setSendendToServer();
                    LocalStorage.getInstance(ctx).setByTag(LocalStorage.TAG_KEY,LocalStorage.NULL_VALUE);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.v("Debug","DEU ERRO");
        }
    });
    queue.add(stringRequest);
}
项目:Codeforces    文件:HurlStack.java   
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
项目:Android-Code-Demos    文件:MainActivity.java   
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();
}
项目:TheMovies    文件:MoviesTask.java   
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);
}
项目:GitHub    文件:ImageLoader.java   
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);
        }
    });
}
项目:Codeforces    文件:MockHttpStack.java   
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws AuthFailureError {
    mLastUrl = request.getUrl();
    mLastHeaders = new HashMap<String, String>();
    if (request.getHeaders() != null) {
        mLastHeaders.putAll(request.getHeaders());
    }
    if (additionalHeaders != null) {
        mLastHeaders.putAll(additionalHeaders);
    }
    try {
        mLastPostBody = request.getBody();
    } catch (AuthFailureError e) {
        mLastPostBody = null;
    }
    return mResponseToReturn;
}
项目:boohee_v5.6    文件:OkHttpStack.java   
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
        this.mSslSocketFactory = sc.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (b.a.equals(url.getProtocol()) && this.mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(this.mSslSocketFactory);
    }
    return connection;
}
项目:TheMovies    文件:MoviesTask.java   
private static void requestGetTrailers(String url, final GetTrailersCallback callback,
                                         Activity activity) {

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    callback.successGetTrailers(MoviesMapping.getTrailersFromResponse(response));
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    callback.errorGetTrailers();
                }
            });
    VolleyHelper.getInstance(activity).addToRequestQueue(request, activity);
}
项目:android-advanced-light    文件:MainActivity.java   
private void UseJsonRequest() {
    String requestBody = "ip=59.108.54.37";
    JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://ip.taobao.com/service/getIpInfo.php?ip=59.108.54.37",
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    IpModel ipModel = new Gson().fromJson(response.toString(), IpModel.class);
                    if (null != ipModel && null != ipModel.getData()) {
                        String city = ipModel.getData().getCity();
                        Log.d(TAG, city);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, error.getMessage(), error);
        }
    }
    );
    mQueue.add(mJsonObjectRequest);
}
项目:omnicrow-android    文件:OmniCrow.java   
public static void trackBeaconEvent(BeaconModel itemModel) {
    if (itemModel == null) {
        throw new OmniCrowAnalyticsSdkNotInitializedException("You must initialize the OmniCrow SDK first");
    }

    RequestModel requestModel = new RequestModel(Request.Method.POST, "event/beacon", null, true, itemModel);
    ServiceOperations.makeRequest(applicationContext, requestModel, new ServiceCallback<ServiceSuccess>() {
        @Override
        public void success(ServiceSuccess result) {
            OmniCrowAnalyticsLogger.writeInfoLog(result.getMessage());
        }

        @Override
        public void error(ServiceException e) {
            OmniCrowAnalyticsLogger.writeErrorLog(e.getMessage());

        }
    }, new TypeToken<ServiceSuccess>() {
    });

}
项目:stitch-android-sdk    文件:Auth.java   
/**
 * Fetch the current user profile
 *
 * @return profile of the given user
 */
public Task<UserProfile> getUserProfile() {
    return _stitchClient.executeRequest(
            Request.Method.GET,
            Paths.USER_PROFILE
    ).continueWith(new Continuation<String, UserProfile>() {
        @Override
        public UserProfile then(@NonNull Task<String> task) throws Exception {
            if (!task.isSuccessful()) {
                throw task.getException();
            }

            try {
                _userProfile = _objMapper.readValue(task.getResult(), UserProfile.class);
            } catch (final IOException e) {
                Log.e(TAG, "Error parsing user response", e);
                throw e;
            }

            return _userProfile;
        }
    });
}
项目:CompassDemo    文件:SelectedStatusActivity.java   
protected void GetBorrowerMoney()
{
    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(""))
                    {
                        BorrowerMoney = 0;
                    }
                    BorrowerMoney = Integer.parseInt(response);
                    GetAmount();
                }

            }, 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", Borrower);
        return params;
    }} ;
    requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringgetfund);
}
项目:CompassDemo    文件:BrokerLoanActivity.java   
protected void SendRequest()
{
    SharedPreferences sharedPreferences = getSharedPreferences(UserPref.getSharedPrefName(), Context.MODE_PRIVATE);
    final String  ID = sharedPreferences.getString(UserPref.getKeyUserId(),"Null");
    StringRequest stringGetRequest = new StringRequest(Request.Method.POST, UserPref.getBrokerloansUrl(),
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response)
                {
                    ParseJSON(response);
                }

            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            Toast.makeText(BrokerLoanActivity.this,error.toString(),Toast.LENGTH_SHORT).show();

        }
    }){            @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put(UserPref.getKeyUserId(), ID);
        return params;
    }} ;
    requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringGetRequest);

}
项目:GitHub    文件:BasicNetwork.java   
/**
 * 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));
}
项目:trvlr-android    文件:BaseDrawerActivity.java   
private void loadTravelerId() {
    if (travelerId > 0) return;

    Map<String, String> params = new HashMap();

    String firebaseId = "";
    String firebaseToken = "";

    try {
        firebaseId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        firebaseToken = FirebaseAuth.getInstance().getCurrentUser().getToken(false).getResult().getToken();
    } catch (Exception e) {
        e.printStackTrace();
    }

    params.put("firebaseId", firebaseId);
    params.put("firebaseToken", firebaseToken);
    JSONObject parameters = new JSONObject(params);

    AppController.getInstance().addToRequestQueue(new JsonObjectRequest(
            Request.Method.POST,
            "http://trvlr.ch:8080/api/traveler/auth",
            parameters,
            loadTravelerIdSuccess(),
            loadError()
    ));
}
项目:GeekZone    文件:HttpClientStack.java   
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
项目:Spitfire    文件:UploadRequestTest.java   
@Test
public void listernerCall_success() throws Exception {
    UploadFileRequest.Builder<DummyResponse> builder = new UploadFileRequest.Builder<>(Request.Method.POST, url, DummyResponse.class);
    builder.listener(listener);
    builder.partData(dummyData);
    UploadFileRequest<DummyResponse> baseRequest = builder.build();

    mDelivery.postResponse(baseRequest, mSuccessResponse);
    Mockito.verify(listener, Mockito.times(1)).onSuccess(Mockito.eq(baseRequest), Mockito.isNull(NetworkResponse.class), Mockito.any(DummyResponse.class));
}
项目:GitHub    文件:MockNetwork.java   
@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);
}
项目:iosched-reader    文件:BasicNetwork.java   
/**
 * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
 */
private void logSlowRequests(long requestLifetime, Request<?> request,
        byte[] responseContents, StatusLine statusLine) {
    if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
        VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " +
                "[rc=%d], [retryCount=%s]", request, requestLifetime,
                responseContents != null ? responseContents.length : "null",
                statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount());
    }
}
项目:EsperantoRadio    文件:GammelDrRadioBackend.java   
@Override
public void hentKanalStreams(final Kanal kanal, Request.Priority priority, final NetsvarBehander netsvarBehander) {
  //return BASISURL + "/channel?includeStreams=true&urn=" + urn;
  App.netkald.kald(null, BASISURL + "/channel/" + kanal.slug + "?includeStreams=true", priority, new NetsvarBehander() {
    @Override
    public void fikSvar(Netsvar s) throws Exception {
      if (s.json != null && !s.uændret) {
        JSONObject o = new JSONObject(s.json);
        kanal.setStreams(parsStreams(o));
        Log.d("Streams parset for = " + s.url);//Data opdateret
      }
      netsvarBehander.fikSvar(s);
    }
  });
}
项目:iosched-reader    文件:HttpClientStack.java   
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
项目:CompassDemo    文件:AccountProfileActivity.java   
protected void SendRequest()
{
    StringRequest stringGetRequest = new StringRequest(Request.Method.POST, UserPref.getAccountprofileUrl(),
            new Response.Listener<String>(){
                @Override
                public void onResponse(String response)
                {
                    ParseJSON(response);
                }

            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            Toast.makeText(AccountProfileActivity.this,error.toString(),Toast.LENGTH_SHORT).show();

        }
    }){            @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put(UserPref.getKeyUserId(), ID);
        return params;
    }};
    requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringGetRequest);

}
项目:gofun-app    文件:TTLNetwork.java   
public void loginUser(final User user, final String deviceToken, final VolleyCallback
        callback) {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, TTLEndpoints
            .URL_USER_LOGIN,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    callback.onSuccess(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error != null && error.getMessage() != null) {
                        callback.onError(error.getMessage());
                    }
                }
            }) {
        @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_PASSWORD, user.getPassword());
            param.put(NetworkKeys.KEY_DEVICE_TOKEN, deviceToken);
            return param;
        }
    };

    AppController.getInstance().addToRequestQueue(stringRequest, TAG);
}
项目:IT405    文件:MainActivity.java   
public void makeRequest(){
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET,
            "http://www.recipepuppy.com/api/?q=apple",
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray responseArray = response.getJSONArray("results");

                        Recipe recipe1 = new Recipe(responseArray.getJSONObject(0));

                        Toast.makeText(getApplicationContext(), recipe1.title, Toast.LENGTH_LONG).show();
                    } catch (Exception e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
                }
            }
    );

    queue.add(jsonObjectRequest);
}
项目:GitHub    文件:BasicNetwork.java   
/**
 * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
 */
private void logSlowRequests(long requestLifetime, Request<?> request,
        byte[] responseContents, StatusLine statusLine) {
    if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
        VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " +
                "[rc=%d], [retryCount=%s]", request, requestLifetime,
                responseContents != null ? responseContents.length : "null",
                statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount());
    }
}
项目:trvlr-android    文件:BaseDrawerActivity.java   
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();
            }
        }
    };
}
项目:CompassDemo    文件:SearchedAccountProfileActivity.java   
protected void UpdateUser()
{
    StringRequest stringGetRequest = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/updateuser.php",
            new Response.Listener<String>(){
                @Override
                public void onResponse(String response)
                {
                    Toast.makeText(SearchedAccountProfileActivity.this, response, Toast.LENGTH_SHORT).show();
                }

            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            Toast.makeText(SearchedAccountProfileActivity.this,error.toString(),Toast.LENGTH_SHORT).show();

        }
    }){            @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.put(UserPref.getKeyUserId(), ID);
        params.put("BorrowerType", BorrowerType);
        params.put("LenderType", LenderType);
        return params;
    }}
            ;
    requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringGetRequest);
}
项目:Codeforces    文件:HurlStack.java   
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}
项目:EsperantoRadio    文件:DrBasicNetwork.java   
/**
 * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
 */
private void logSlowRequests(long requestLifetime, Request<?> request,
                             byte[] responseContents, StatusLine statusLine) {
  if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
    VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " +
            "[rc=%d], [retryCount=%s]", request, requestLifetime,
        responseContents != null ? responseContents.length : "null",
        statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount());
  }
}
项目:LeMondeRssReader    文件:RssService.java   
@Override
protected void onHandleIntent(Intent intent) {
    if (REQUEST_QUEUE == null) {
        REQUEST_QUEUE = Volley.newRequestQueue(this);
    }
    reply = intent.getParcelableExtra(PENDING_RESULT);
    REQUEST_QUEUE.add(new StringRequest(Request.Method.GET, Constants.BASE_URL + intent.getStringExtra(CATEGORY), onFeedReceived, onErrorResponse));
}
项目:BackendDrivenMenu    文件:RequestManager.java   
/**
 * Does a request to a specific service.
 * @param user User for making requests to the protected directory.
 * @param password Password for making requests to the protected directory.
 * @param appController Application class.
 * @param requestTag Name of request.
 * @param url URL address of this service.
 * @param params Map with the request parameters.
 * @param requestManagerResponse Object that manages service response.
 */
public void doRequest(String user, String password, AppController appController, final String requestTag, String url, Map<String, Object> params, final RequestManagerResponse requestManagerResponse) {
    Log.i(TAG, requestTag + " REQUEST: " + params.toString());
    appController.addToRequestQueue(new CustomRequest(user, password, Request.Method.POST, url, params, false,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) { // When the response is successful received
                    Log.i(TAG, requestTag + " RESPONSE: " + response.toString());
                    try {
                        String status = response.getString(Keys.STATUS); // We get the status response
                        JSONObject content = response.getJSONObject(Keys.CONTENT);
                        if (status.equals(Keys.OK)) {
                            if (requestManagerResponse != null)
                                requestManagerResponse.onResponse(true, content, null);
                        } else if (status.equals(Keys.ERROR)) {
                            if (requestManagerResponse != null)
                                requestManagerResponse.onResponse(false, content, null);
                        }
                    } catch (JSONException e) {
                        if (requestManagerResponse != null)
                            requestManagerResponse.onResponse(false, null, e);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError errorResponse) { // When there is an error
                    Log.i(TAG, requestTag + ": " + errorResponse.toString());
                    if (requestManagerResponse != null)
                        requestManagerResponse.onResponse(false, null, errorResponse);
                }
            }), requestTag); // Adding request to request queue
}
项目:BookBarcodeScanner    文件:ListAllBookActivity.java   
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);
    }
项目:CompassDemo    文件:SelectedStatusActivity.java   
protected void CheckRepaid()
{
    StringRequest stringgetfund = new StringRequest(Request.Method.POST, "https://greatnorthcap.000webhostapp.com/PHP/checkrepay.php",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response)
                {
                    if(response.equalsIgnoreCase("Repaid"))
                    {
                        buttonRepayLoan.setVisibility(View.GONE);
                        buttonRepayLoanEther.setVisibility(View.GONE);
                    }
                    else {
                        buttonRepayLoan.setVisibility( View.VISIBLE);
                        buttonRepayLoanEther.setVisibility( View.VISIBLE);
                    }
                }

            }, 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",ID);
        return params;
    }} ;
    requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringgetfund);

}
项目:TrackIt-Android    文件:ActorDetailActivity.java   
private void fetchData() {
    wheel.setVisibility(View.VISIBLE);
    RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
    StringRequest req = new StringRequest(Request.Method.GET, API.BASE_IMAGE_URL + showID + "/actors.xml",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    new loadData().execute(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                tvError.setText(R.string.timeout_error);
            } else if (error instanceof ServerError) {
                tvError.setText(R.string.server_error);
            } else if (error instanceof NetworkError) {
                tvError.setText(R.string.network_error);
            } else {
                tvError.setText(R.string.connection_error);
            }
            tapToRetry.setVisibility(View.VISIBLE);
            wheel.setVisibility(View.GONE);
        }
    });
    requestQueue.add(req);
}
项目:TrackIt-Android    文件:ShowImageActivity.java   
private void fetchData() {
    wheel.setVisibility(View.VISIBLE);
    RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
    StringRequest req = new StringRequest(Request.Method.GET, API.BASE_IMAGE_URL + showID + "/banners.xml",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    final String imageURL = API.TVDB_LINK + "banners/";
                    imageArray.clear();
                    try {
                        JSONObject jsonObjectResponse = XML.toJSONObject(response);
                        JSONArray bannerList = jsonObjectResponse.getJSONObject("Banners").getJSONArray("Banner");

                        for (int i = 0; i < bannerList.length(); i++) {
                            JSONObject imageObject = bannerList.getJSONObject(i);
                            if (imageObject.optString("BannerType").equals(imageName[imageType])) {
                                ShowImageItem imageItem = new ShowImageItem();
                                imageItem.setImagePath(imageURL + imageObject.optString("BannerPath"));
                                String thumbnailPath = imageObject.optString("ThumbnailPath", "");
                                if (!thumbnailPath.equals("")) {
                                    imageItem.setThumbnailPath(imageURL + thumbnailPath);
                                } else {
                                    imageItem.setThumbnailPath("");
                                }
                                imageArray.add(imageItem);
                            }
                        }
                        wheel.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        wheel.setVisibility(View.GONE);
                        Log.e("ShowImageActivity", String.valueOf(e));
                        tvError.setText(R.string.no_images_available);
                        tapToRetry.setVisibility(View.VISIBLE);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error instanceof TimeoutError) {
                tvError.setText(R.string.timeout_error);
            } else if (error instanceof ServerError) {
                tvError.setText(R.string.server_error);
            } else {
                tvError.setText(R.string.connection_error);
            }
            tapToRetry.setVisibility(View.VISIBLE);
            wheel.setVisibility(View.GONE);
        }
    });
    requestQueue.add(req);
}