Android異步Http網絡請求訪問服務器端的用法

1.首先添加android-async-http-1.4.5.jar這個包,可以在網上下載到;

2.手寫一個工具類HttpUtils,添加一個靜態方法用來調用:

       //request_str是請求參數,mContext 上下文對象 ,asyncHttpHandler 處理服務器端響應的對象 ,url 請求地址

       public static void newPostData(String request_str, Context mContext,
            AsyncHttpResponseHandler asyncHttpHandler,String url) {
        try {
            AsyncHttpClient client = new AsyncHttpClient();
            StringEntity entity = new StringEntity(request_str);
            client.post(mContext, url, entity,
                    "application/json", asyncHttpHandler);
            
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


3.調用    HttpUtils.newPostData("", mContext, asyncHttpHandler,
                    AppConfig.jinpinUrl);



4.處理服務器端的響應:

private AsyncHttpResponseHandler asyncHttpHandler = new AsyncHttpResponseHandler() {

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

                //網絡請求失敗
           
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            // TODO Auto-generated method stub
            //網絡請求成功,arg2是返回的數據字節數組

        }

    };



發佈了17 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章