Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 異步Http框架簡介和實現原理

Android 異步Http框架簡介和實現原理

編輯:關於Android編程

在前幾篇文章中《Android 采用get方式提交數據到服務器》《Android 采用post方式提交數據到服務器》《Android 采用HttpClient提交數據到服務器》介紹了android的兩種提交數據到服務器的方法

本文將介紹另外一種基於框架android-async-http的方法來實現

android-async-http是一個強大的網絡請求庫,這個網絡請求庫是基於Apache HttpClient庫之上的一個異步網絡請求處理庫,網絡處理均基於Android的非UI線程,通過回調方法處理請求結果。android-async-http是一個強大的第三方開源網絡請求庫

官網源碼:https://github.com/loopj/android-async-http

官網教程:http://loopj.com/android-async-http/

新建項目,先到github上:https://github.com/loopj/android-async-http/tree/1.4.0

下載相應的zip文件,解壓縮後將src中的com文件夾復制到項目的src目錄

\

下面使用框架android-async-http,代碼如下:

package com.wuyudong.asynchttp;

import java.net.URLEncoder;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        // 用戶名密碼提交到服務器
        AsyncHttpClient client = new AsyncHttpClient();
        String path = "http://169.254.168.71:8080/web/LoginServlet?username="
                + URLEncoder.encode("wuyudong") + "&password="
                + URLEncoder.encode("123");

        client.get(path, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                // TODO Auto-generated method stub
                super.onSuccess(content);
                Toast.makeText(MainActivity.this, "請求成功!", 0).show();
            }

            @Override
            public void onFailure(Throwable error, String content) {
                // TODO Auto-generated method stub
                super.onFailure(error, content);
                Toast.makeText(MainActivity.this, "請求失敗!", 0).show();
            }
        });

    }

}

可以看到代碼量減少了很多


下面來實現一個精簡版的異步框架

新建項目

\

AsyncHttpClient.java

package com.wuyudong.AsyncClient;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Message;

public class AsyncHttpClient {

    public void get(final String path, final MyHandler myHandler) {

        new Thread() {
            @Override
            public void run() {

                HttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(path);

                try {
                    HttpResponse response = client.execute(httpGet);
                    InputStream is = response.getEntity().getContent();
                    String content = StreamTools.readInputStream(is);

                    // 執行成功
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = "請求成功";
                    myHandler.sendMessage(msg);

                } catch (Exception e) {
                    e.printStackTrace();
                    // 執行失敗
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = "請求失敗";
                    myHandler.sendMessage(msg);
                }

            }
        }.start();

    }

}

MainActivity.java

package com.wuyudong.AsyncClient;

import java.net.URLEncoder;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        // 1、開啟子線程 執行一個http請求,在後台執行 在子線程執行

        // 2、 子線程執行完畢後通知ui界面

        AsyncHttpClient client = new AsyncHttpClient();
        String path = "http://169.254.168.71:8080/web/LoginServlet?username="
                + URLEncoder.encode("wuyudong") + "&password="
                + URLEncoder.encode("123");
        client.get(path, new MyHandler() {
            @Override
            public void onFailure(String content) {
                Toast.makeText(MainActivity.this, content, 1).show();
                super.onFailure(content);

            }

            @Override
            public void onSuccess(String content) {
                Toast.makeText(MainActivity.this, content, 0).show();
                super.onSuccess(content);

            }
        });

    }
}

MyHandler.java

package com.wuyudong.AsyncClient;

import android.os.Handler;
import android.os.Message;

public class MyHandler extends Handler {
    public void onFailure(String content) {

    }

    public void onSuccess(String content) {

    }

    @Override
    public void handleMessage(Message msg) {
        String content = (String) msg.obj;
        switch (msg.what) {
        case 0:
            onSuccess(content);
            break;

        case 1:
            onFailure(content);
            break;
        default:
            break;
        }
        super.handleMessage(msg);
    }
}

StreamTools.java

package com.wuyudong.AsyncClient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTools {
    /**
     * 把輸入流的內容轉化成字符串
     * 
     * @param is
     * @return
     */
    public static String readInputStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            baos.close();
            byte[] result = baos.toByteArray();

            String str = new String(result);
            // 試著解析result裡面的字符串
            if (str.contains("gb2312")) {
                return new String(result, "gb2312");
            } else if(str.contains("utf-8")){
                return str;
            } else {
                return null;
            }
            
            //return new String(result, "gb2312");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved