Search in sources :

Example 1 with Request

use of com.android.volley.Request in project BestPracticeApp by pop1234o.

the class MainActivity method requestOkHttp.

/**
 * 缓存
 */
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();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) StringRequest(com.android.volley.toolbox.StringRequest) Request(com.android.volley.Request) IOException(java.io.IOException) Response(com.android.volley.Response) CacheControl(okhttp3.CacheControl) Interceptor(okhttp3.Interceptor) Cache(com.android.volley.Cache) DiskBasedCache(com.android.volley.toolbox.DiskBasedCache)

Example 2 with Request

use of com.android.volley.Request in project fresco by facebook.

the class VolleyNetworkFetcher method fetch.

@Override
public void fetch(final VolleyNetworkFetchState fetchState, final Callback callback) {
    fetchState.submitTime = SystemClock.elapsedRealtime();
    final RawRequest request = new RawRequest(fetchState.getUri().toString(), new Response.Listener<byte[]>() {

        @Override
        public void onResponse(byte[] bytes) {
            fetchState.responseTime = SystemClock.uptimeMillis();
            try {
                InputStream is = new ByteArrayInputStream(bytes);
                callback.onResponse(is, bytes.length);
            } catch (IOException e) {
                callback.onFailure(e);
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError volleyError) {
            callback.onFailure(volleyError);
        }
    });
    fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks() {

        @Override
        public void onCancellationRequested() {
            mRequestQueue.cancelAll(new RequestFilter() {

                @Override
                public boolean apply(Request<?> candidate) {
                    return candidate != null && request.getSequence() == candidate.getSequence();
                }
            });
        }
    });
    mRequestQueue.add(request);
}
Also used : VolleyError(com.android.volley.VolleyError) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Request(com.android.volley.Request) IOException(java.io.IOException) BaseProducerContextCallbacks(com.facebook.imagepipeline.producers.BaseProducerContextCallbacks) Response(com.android.volley.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) RequestFilter(com.android.volley.RequestQueue.RequestFilter)

Example 3 with Request

use of com.android.volley.Request in project saga-android by AnandChowdhary.

the class Updater method checkForUpdates.

public static void checkForUpdates(final Context context, boolean visibility) {
    final int versionCode = getVersionCode(context);
    final ProgressDialog progressDialog = new ProgressDialog(context);
    String updateUrl = "https://www.dropbox.com/s/bka9o3p43oki217/saga.json?raw=1";
    if (visibility) {
        progressDialog.setTitle(context.getString(R.string.update));
        progressDialog.setMessage(context.getString(R.string.update_checking));
        progressDialog.setCancelable(true);
        progressDialog.show();
    }
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, updateUrl, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                int updateVersionCode = response.getInt("versionCode");
                if (updateVersionCode > versionCode && versionCode != 0) {
                    if (progressDialog.isShowing()) {
                        progressDialog.cancel();
                    }
                    final String apkUrl = response.getString("apkUrl");
                    String changelog = response.getString("changelog");
                    AlertDialog dialog = new AlertDialog.Builder(context).setTitle(context.getString(R.string.new_update)).setMessage(changelog).setPositiveButton(context.getString(R.string.update_now), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            File myFile = new File(Utils.getStoragePath(context), "update.apk");
                            if (myFile.exists())
                                myFile.delete();
                            Uri uri = Uri.parse(apkUrl);
                            DownloadManager dMgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                            DownloadManager.Request dr = new DownloadManager.Request(uri);
                            String filename = "update.apk";
                            dr.setTitle(context.getString(R.string.app_name) + " " + context.getString(R.string.update));
                            dr.setDestinationUri(Uri.fromFile(new File(Utils.getStoragePath(context) + "/" + filename)));
                            // dr.setDestinationInExternalPublicDir("/Saga/", filename);
                            dMgr.enqueue(dr);
                        }
                    }).setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).setCancelable(false).create();
                    dialog.show();
                } else {
                    if (progressDialog.isShowing()) {
                        progressDialog.cancel();
                        Toast.makeText(context, context.getString(R.string.no_update), Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            if (progressDialog.isShowing()) {
                progressDialog.cancel();
                Toast.makeText(context, context.getString(R.string.error_connect), Toast.LENGTH_SHORT).show();
            }
        }
    });
    request.setShouldCache(false);
    VolleySingleton.getInstance(context).getRequestQueue().add(request);
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) VolleyError(com.android.volley.VolleyError) DialogInterface(android.content.DialogInterface) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) Request(com.android.volley.Request) JSONException(org.json.JSONException) ProgressDialog(android.app.ProgressDialog) Uri(android.net.Uri) DownloadManager(android.app.DownloadManager) Response(com.android.volley.Response) JSONObject(org.json.JSONObject) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) File(java.io.File)

Example 4 with Request

use of com.android.volley.Request in project OkVolley by googolmo.

the class OkHttpStack method performRequest.

/**
 * perform the request
 *
 * @param request           request
 * @param additionalHeaders headers
 * @return http response
 * @throws java.io.IOException
 * @throws com.android.volley.AuthFailureError
 */
@Override
public Response performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();
    builder.url(url);
    for (String headerName : map.keySet()) {
        builder.header(headerName, map.get(headerName));
        // connection.addRequestProperty(headerName, map.get(headerName));
        if (VolleyLog.DEBUG) {
            // print header message
            VolleyLog.d("RequestHeader: %1$s:%2$s", headerName, map.get(headerName));
        }
    }
    setConnectionParametersForRequest(builder, request);
    // Initialize HttpResponse with data from the okhttp.
    Response okHttpResponse = mClient.newCall(builder.build()).execute();
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    return okHttpResponse;
}
Also used : Response(com.squareup.okhttp.Response) HashMap(java.util.HashMap) Request(com.android.volley.Request) IOException(java.io.IOException)

Example 5 with Request

use of com.android.volley.Request in project FastDev4Android by jiangqqlmj.

the class BasicNetworkTest method headersAndPostParams.

@Test
public void headersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) {

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            return null;
        }

        @Override
        protected void deliverResponse(String response) {
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestheader", "foo");
            return result;
        }

        @Override
        public Map<String, String> getParams() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestpost", "foo");
            return result;
        }
    };
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
}
Also used : StringEntity(org.apache.http.entity.StringEntity) MockHttpStack(com.android.volley.mock.MockHttpStack) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HashMap(java.util.HashMap) Request(com.android.volley.Request) NetworkResponse(com.android.volley.NetworkResponse) ProtocolVersion(org.apache.http.ProtocolVersion) Test(org.junit.Test)

Aggregations

Request (com.android.volley.Request)14 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 Response (com.android.volley.Response)5 StringRequest (com.android.volley.toolbox.StringRequest)5 VolleyError (com.android.volley.VolleyError)4 StringEntity (org.apache.http.entity.StringEntity)4 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)4 NetworkResponse (com.android.volley.NetworkResponse)3 MockHttpStack (com.android.volley.mock.MockHttpStack)3 OkHttpClient (okhttp3.OkHttpClient)3 ProtocolVersion (org.apache.http.ProtocolVersion)3 DownloadManager (android.app.DownloadManager)2 Uri (android.net.Uri)2 Response (com.squareup.okhttp.Response)2 DeleteRequest (io.swagger.client.request.DeleteRequest)2 GetRequest (io.swagger.client.request.GetRequest)2 PatchRequest (io.swagger.client.request.PatchRequest)2 PostRequest (io.swagger.client.request.PostRequest)2 PutRequest (io.swagger.client.request.PutRequest)2