loopj----Android Asynchronous Http Client(AHC)

新建工具類,方便調用:

package com.blueware.rpm.util;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

public class HttpUtil {
    private static     AsyncHttpClient client; //實例話對象
    
    public static void get(String urlString,AsyncHttpResponseHandler res)    //用一個完整url獲取一個string對象
    {
        client.get(urlString, res);
    }
    public static void post(String urlString,AsyncHttpResponseHandler res)    
    {
        client.post(urlString, res);
    }
    public static void get(String urlString,RequestParams params,AsyncHttpResponseHandler res)   //url裏面帶參數
    {
        client.get(urlString, params,res);
    }
    public static void post(String urlString, RequestParams params, AsyncHttpResponseHandler res) {
        client.post(urlString, params, res);
    }
    
    public static void get(String urlString,JsonHttpResponseHandler res)   //不帶參數,獲取json對象或者數組
    {
        client.get(urlString, res);
    }
    public static void post(String urlString,JsonHttpResponseHandler res)   
    {
        client.post(urlString, res);
    }
    public static void get(String urlString,RequestParams params,JsonHttpResponseHandler res)   //帶參數,獲取json對象或者數組
    {
        client.get(urlString, params,res);
    }
    public static void post(String urlString,RequestParams params,JsonHttpResponseHandler res)   
    {
        client.post(urlString, params,res);
    }
    public static void get(String uString, BinaryHttpResponseHandler bHandler)   //下載數據使用,會返回byte數據
    {
        client.get(uString, bHandler);
    }
    public static void post(String uString, BinaryHttpResponseHandler bHandler)  
    {
        client.post(uString, bHandler);
    }
    public static AsyncHttpClient getClient()
    {
        return client;
    }
}

就很容易的在需要請求網路的地方發送 網絡請求:

import org.json.*;
import com.loopj.android.http.*;

class TwitterRestClientUsage {
    public void getPublicTimeline() throws JSONException {
        <pre name="code" class="java">    HttpUtil<span style="font-family: Arial;">.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {</span>
@Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // If the response is JSONObject instead of expected JSONArray } @Override public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) { // Pull out the first event on the public timeline JSONObject firstEvent = timeline.get(0); String tweetText = firstEvent.getString("text"); // Do something with the response System.out.println(tweetText); } }); }}


使用PersistentCookieStore保存Cookie
這個庫包含一個PersistentCookieStore ,這個類是Apache HttpClient CookieStore 接口的實現,它可以自動將cookies保存到SharedPreferences 。
如果你需要使用cookie保持認證會話,這將是特別重要的,因爲即使用戶關掉了應用仍然可以登錄狀態。
首先,創建一個AsyncHttpClient對象:
AsyncHttpClient myClient = new AsyncHttpClient();

現在將client的Cookie保存到一個PersistentCookieStore,構造方法需要有一個上下文(Activity,Application都可以,通常this就OK了)。

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);

注意:

以上工具類適合於HTTP請求,若是HTTPS請求,須在工具類中加一段代碼:

private static boolean isSSL=true;
    static
    {   
    	if(!isSSL){
    	 client =new AsyncHttpClient(); 
    	}else{
    		client = new AsyncHttpClient(true, 80, 443);
    	}
    	 client.setEnableRedirects(false);//設置不允許重定向
        client.setTimeout(10000);   //設置鏈接超時,如果不設置,默認爲10s
    }
大笑OK了

Https請求下將client的Cookie保存到一個PersistentCookieStore

public void sentPostMessage() {
		String urlString = ApiConfig.LOGIN;
		RequestParams params = new RequestParams();
		params.put("username", emailEditText.getText().toString());
		params.put("password", passwdEditText.getText().toString());
		<span style="background-color: rgb(255, 204, 153);">AsyncHttpClient myClient=new AsyncHttpClient(true, 80, 443);
		PersistentCookieStore myCookieStore=new PersistentCookieStore(this);
		myClient.setCookieStore(myCookieStore);
		myClient.setEnableRedirects(false);
		myClient</span>.post(urlString, params, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				Toast.makeText(LoginActivity.this, "登錄失敗,請檢查用戶名密碼是否正確" + arg1[1],
						Toast.LENGTH_LONG).show();
				checkEmail();
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
。。。。。
          }
		});

	}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章