Android Open Source - NetworkFacade Ok Http Client






From Project

Back to project page NetworkFacade.

License

The source code is released under:

Apache License

If you think the Android project NetworkFacade listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.saguinav.networkfacade.sample;
/*  w  w  w  .  j ava 2s .com*/
import android.content.Context;
import android.os.Handler;

import com.saguinav.networkfacade.HttpBody;
import com.saguinav.networkfacade.HttpClient;
import com.saguinav.networkfacade.HttpError;
import com.saguinav.networkfacade.HttpRequest;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.apache.http.HttpStatus;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class OkHttpClient implements HttpClient {

    /** Default on-disk cache directory. */
    private static final String DEFAULT_CACHE_DIR = "okhttp";
    /** Default maximum disk usage in bytes. */
    private static final int DEFAULT_DISK_USAGE_BYTES = 5 * 1024 * 1024; // 5 MiB

    private final Context mContext;
    private final com.squareup.okhttp.OkHttpClient mOkHttpClient;

    public OkHttpClient(Context context) throws IOException {
        mContext = context;
        mOkHttpClient = new com.squareup.okhttp.OkHttpClient();

        final File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
        mOkHttpClient.setCache(new Cache(cacheDir, DEFAULT_DISK_USAGE_BYTES));
    }

    @Override
    public void performRequest(HttpRequest request, final ResponseListener responseListener) {
        final Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(request.getUrl());

        switch (request.getMethod()) {
            case GET:
                requestBuilder.get();
                break;

            case POST:
                requestBuilder.post(getHttpBody(request.getBody()));
                break;

            case PUT:
                requestBuilder.put(getHttpBody(request.getBody()));
                break;

            case DELETE:
                requestBuilder.delete();
                break;
        }

        if (request.getHeaders() != null) {
            final Set<Map.Entry<String, String>> entrySet = request.getHeaders().entrySet();

            for(Map.Entry<String, String> entry : entrySet) {
                requestBuilder.header(entry.getKey(), entry.getValue());
            }
        }

        final MainThreadResponseListenerWrapper
            wrappedListener = new MainThreadResponseListenerWrapper(mContext, responseListener);

        mOkHttpClient.newCall(requestBuilder.build()).enqueue(new Callback() {

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    wrappedListener.onSuccess(response.body().string());
                } else {
                    HttpError.Code errorCode;

                    if (response.networkResponse() == null) {
                        errorCode = HttpError.Code.NETWORK;
                    } else if (response.code() >= HttpStatus.SC_BAD_REQUEST &&
                               response.code() < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                        errorCode = HttpError.Code.CLIENT;

                        if (response.body() != null) {
                            wrappedListener.onFailure(new HttpError(errorCode,
                                                             response.body().string()));
                        }
                    } else {
                        errorCode = HttpError.Code.SERVER;
                    }

                    wrappedListener.onFailure(new HttpError(errorCode));
                }
            }

            @Override
            public void onFailure(Request request, IOException e) {
                wrappedListener.onFailure(new HttpError(HttpError.Code.UNKNOWN, e));
            }

        });
    }

    private static RequestBody getHttpBody(HttpBody httpBody) {
        if (httpBody == null) {
            return null;
        }

        final MediaType mediaType = MediaType.parse(httpBody.getType() + "; charset=" +
                                                    httpBody.getEncoding());

        return RequestBody.create(mediaType, httpBody.getContent());
    }

    private static class MainThreadResponseListenerWrapper implements ResponseListener {

        private final Handler mHandler;
        private final ResponseListener mListener;

        public MainThreadResponseListenerWrapper(Context context, ResponseListener listener) {
            mHandler = new Handler(context.getMainLooper());
            mListener = listener;
        }

        @Override
        public void onSuccess(final String response) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    mListener.onSuccess(response);
                }

            });
        }

        @Override
        public void onFailure(final HttpError error) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    mListener.onFailure(error);
                }

            });
        }

    }

}




Java Source Code List

com.android.volley.toolbox.AuthenticationChallengesProofHurlStack.java
com.saguinav.networkfacade.ApplicationTest.java
com.saguinav.networkfacade.HttpBody.java
com.saguinav.networkfacade.HttpClient.java
com.saguinav.networkfacade.HttpError.java
com.saguinav.networkfacade.HttpRequest.java
com.saguinav.networkfacade.RetryPolicy.java
com.saguinav.networkfacade.sample.HeadlessFragment.java
com.saguinav.networkfacade.sample.HttpClientSingleton.java
com.saguinav.networkfacade.sample.MainActivity.java
com.saguinav.networkfacade.sample.OkHttpApplication.java
com.saguinav.networkfacade.sample.OkHttpClient.java
com.saguinav.networkfacade.sample.RepositoriesDeserializer.java
com.saguinav.networkfacade.sample.Repository.java
com.saguinav.networkfacade.sample.SimpleURLBuilder.java
com.saguinav.networkfacade.sample.VolleyApplication.java
com.saguinav.networkfacade.sample.VolleyHttpClient.java