com.fihmi.tools.minet.MiHttpResponseHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.fihmi.tools.minet.MiHttpResponseHandler.java

Source

/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
    http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.fihmi.tools.minet;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import org.apache.http.Header;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.util.EntityUtils;

public class MiHttpResponseHandler {
    protected static final int SUCCESS_MESSAGE = 0;
    protected static final int FAILURE_MESSAGE = 1;
    protected static final int START_MESSAGE = 2;
    protected static final int FINISH_MESSAGE = 3;

    private Handler handler;

    /**
     * Creates a new AsyncHttpResponseHandler
     */
    @SuppressLint("HandlerLeak")
    public MiHttpResponseHandler() {
        // Set up a handler to post events back to the correct thread if possible
        if (Looper.myLooper() != null) {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    MiHttpResponseHandler.this.handleMessage(msg);
                }
            };
        }
    }

    public void onStart(final int request_tag) {
    }

    public void onFinish(final int request_tag) {
    }

    public void onSuccess(int statusCode, Header[] headers, String content, final int request_tag) {
    }

    /**
     * Fired when a request fails to complete, override to handle in your own code
     * @param error the underlying cause of the failure
     * @deprecated use {@link #onFailure(Throwable, String)}
     */

    /**
     * Fired when a request fails to complete, override to handle in your own code
     * @param error the underlying cause of the failure
     * @param content the response body, if any
     */
    public void onFailure(Throwable error, String content, final int request_tag) {
        // By default, call the deprecated onFailure(Throwable) for compatibility
    }

    //
    // Pre-processing of messages (executes in background threadpool thread)
    //

    protected void sendSuccessMessage(int statusCode, Header[] headers, String responseBody,
            final int request_tag) {
        sendMessage(obtainMessage(SUCCESS_MESSAGE,
                new Object[] { Integer.valueOf(statusCode), headers, responseBody }, request_tag));
    }

    protected void sendFailureMessage(Throwable e, String responseBody, final int request_tag) {
        sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[] { e, responseBody }, request_tag));
    }

    protected void sendFailureMessage(Throwable e, byte[] responseBody, final int request_tag) {
        sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[] { e, responseBody }, request_tag));
    }

    protected void sendStartMessage(final int request_tag) {
        sendMessage(obtainMessage(START_MESSAGE, null, request_tag));
    }

    protected void sendFinishMessage(final int request_tag) {
        sendMessage(obtainMessage(FINISH_MESSAGE, null, request_tag));
    }

    //
    // Pre-processing of messages (in original calling thread, typically the UI thread)
    //

    protected void handleSuccessMessage(int statusCode, Header[] headers, String responseBody,
            final int request_tag) {
        onSuccess(statusCode, headers, responseBody, request_tag);
    }

    protected void handleFailureMessage(Throwable e, String responseBody, final int request_tag) {
        onFailure(e, responseBody, request_tag);
    }

    // Methods which emulate android's Handler and Message methods
    protected void handleMessage(Message msg) {
        Object[] response;
        final int request_tag = msg.arg1;
        switch (msg.what) {
        case SUCCESS_MESSAGE:
            response = (Object[]) msg.obj;
            handleSuccessMessage(((Integer) response[0]).intValue(), (Header[]) response[1], (String) response[2],
                    request_tag);
            break;
        case FAILURE_MESSAGE:
            response = (Object[]) msg.obj;
            handleFailureMessage((Throwable) response[0], (String) response[1], request_tag);
            break;
        case START_MESSAGE:
            onStart(request_tag);
            break;
        case FINISH_MESSAGE:
            onFinish(request_tag);
            break;
        }
    }

    protected void sendMessage(Message msg) {
        if (handler != null) {
            handler.sendMessage(msg);
        } else {
            handleMessage(msg);
        }
    }

    protected Message obtainMessage(int responseMessage, Object response, final int request_tag) {
        Message msg = null;
        if (handler != null) {
            msg = this.handler.obtainMessage(responseMessage, response);
            msg.arg1 = request_tag;
        } else {
            msg = Message.obtain();
            msg.what = responseMessage;
            msg.obj = response;
            msg.arg1 = request_tag;
        }
        return msg;
    }

    // Interface to AsyncHttpRequest
    void sendResponseMessage(HttpResponse response, final int request_tag) {
        StatusLine status = response.getStatusLine();
        String responseBody = null;
        try {
            HttpEntity entity = null;
            HttpEntity temp = response.getEntity();
            if (temp != null) {
                entity = new BufferedHttpEntity(temp);
                responseBody = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException e) {
            sendFailureMessage(e, (String) null, request_tag);
        }

        if (status.getStatusCode() >= 300) {
            sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                    responseBody, request_tag);
        } else {
            sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, request_tag);
        }
    }
}