【移動應(yīng)用開發(fā)技術(shù)】怎么在Android中對volley進(jìn)行封裝_第1頁
【移動應(yīng)用開發(fā)技術(shù)】怎么在Android中對volley進(jìn)行封裝_第2頁
【移動應(yīng)用開發(fā)技術(shù)】怎么在Android中對volley進(jìn)行封裝_第3頁
【移動應(yīng)用開發(fā)技術(shù)】怎么在Android中對volley進(jìn)行封裝_第4頁
【移動應(yīng)用開發(fā)技術(shù)】怎么在Android中對volley進(jìn)行封裝_第5頁
已閱讀5頁,還剩8頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

【移動應(yīng)用開發(fā)技術(shù)】怎么在Android中對volley進(jìn)行封裝

本篇文章給大家分享的是有關(guān)怎么在Android中對volley進(jìn)行封裝,在下覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著在下一起來看看吧。public

void

get()

{

String

url

=

"/cc/json/mobile_tel_segment.htm?tel=";

StringRequest

request

=

new

StringRequest(Request.Method.GET,

url,

new

Response.Listener<String>()

{

@Override

public

void

onResponse(String

s)

{

Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();

}

},

new

Response.ErrorListener()

{

@Override

public

void

onErrorResponse(VolleyError

volleyError)

{

Toast.makeText(MainActivity.this,volleyError.toString(),Toast.LENGTH_SHORT).show();

}

});

request.setTag("abcGet");

MyApplication.getHttpQueues().add(request);

}首先看一下我封裝后的使用例子:

private

void

initData()

{

NewsApi.getInfo(new

NetCallback<News>()

{

@Override

public

void

OnSuccess(final

News

result)

{

mAdapter.setData(result.getResult().getData());

}

@Override

public

void

OnError(RestfulError

error)

{

}

});

}有沒有看起來很舒服的感覺。好吧,讓我開始盤它吧!1.首先我先去寫了一個(gè)基類,用來創(chuàng)建一個(gè)新的request并把它加入到volley內(nèi)部封裝的請求隊(duì)列中,代碼如下:public

abstract

class

AuthenticatedRequestBase<T>

extends

Request<T>

{

private

final

static

String

TAG

=

"AuthenticatedRequestBase";

private

static

final

int

TIME_OUT

=

30000;

private

static

final

int

MAX_RETRIES

=

1;

private

static

final

float

BACKOFF_MULT

=

2f;

protected

Context

mContext;

protected

RequestQueue

mRequestQueue;

/**

*

創(chuàng)建新的請求,并把請求加入到請求隊(duì)列requestQueue中

*

*

@param

method

*

@param

url

*

@param

cache

*

@param

errorListener

*/

@SuppressLint("LongLogTag")

public

AuthenticatedRequestBase(int

method,

String

url,

boolean

cache,

Response.ErrorListener

errorListener)

{

super(method,

url,

errorListener);

//this.setShouldCache(cache);

this.setRetryPolicy(new

DefaultRetryPolicy(

TIME_OUT,

MAX_RETRIES,

BACKOFF_MULT));

mRequestQueue

=

YZ.getInstance().getRequestQueue();

if

(mRequestQueue

==

null)

{

throw

new

IllegalArgumentException("mRequestQueue

can't

be

null");

}

mContext

=

YZ.getInstance().getContext();

if

(mContext

==

null)

{

throw

new

IllegalArgumentException("mContext

can't

be

null");

}

//如果重新發(fā)出服務(wù)器請求的時(shí)候,需要清除之前的緩存。

if

(!cache)

{

Cache

volleyCache

=

mRequestQueue.getCache();

Cache.Entry

cacheEntry

=

volleyCache.get(url);

if

(cacheEntry

!=

null)

{

volleyCache.remove(url);

Log.d(TAG,

"remove

volley

cache:"

+

url);

}

}

mRequestQueue.add(this);

}

/**

*

重寫這個(gè)方法,可以在http請求頭里面加入token,客戶端能接受的數(shù)據(jù)類型

*

*

@return

*

@throws

AuthFailureError

*/

@CallSuper

@Override

public

Map<String,

String>

getHeaders()

throws

AuthFailureError

{

Map<String,

String>

headers

=

new

HashMap<>();

String

token

=

"";

//headers.put("Authorization",

"bearer

"

+

token);

//針對Get方法,申明接受的enum類型

//

headers.put("Accept",

"charset=utf-8");

return

headers;

}

/**

*

網(wǎng)絡(luò)錯(cuò)誤問題統(tǒng)一處理

*

*

@param

volleyError

*

@return

*/

@CallSuper

@Override

protected

VolleyError

parseNetworkError(VolleyError

volleyError)

{

return

super.parseNetworkError(volleyError);

}

}代碼注釋比較清晰,就不在贅述。2.以get方法為例,新建一個(gè)GetRequest去繼承這個(gè)基類,并出解析結(jié)果:public

class

GetRequest<TResponse>

extends

AuthenticatedRequestBase<TResponse>

{

private

final

Response.Listener<TResponse>

listener;

private

final

Class<TResponse>

clazz;

private

final

static

String

TAG

=

"GetRequest";

private

String

mUrl;

private

NetCallback<TResponse>

cb;

private

boolean

cacheHit;

public

GetRequest(String

url,

Class<TResponse>

clazz,

boolean

cache,

NetCallback<TResponse>

callback)

{

super(Request.Method.GET,

url,

cache,

callback.getErrorListener());

this.listener

=

callback.getSuccessListener();

this.clazz

=

clazz;

this.mUrl

=

url;

this.cb

=

callback;

//無網(wǎng)絡(luò)時(shí)300ms后返回callback

if

(!NetUtils.isConnect(mContext)

&&

mRequestQueue.getCache().get(url)

==

null)

{

Handler

handler

=

new

Handler();

handler.postDelayed(new

Runnable()

{

@Override

public

void

run()

{

cb.OnNetworkOff();

}

},

300);

}

}

/**

*

這個(gè)是緩存的標(biāo)記,與本地緩存相關(guān)

*

@param

tag

*/

@Override

public

void

addMarker(String

tag)

{

super.addMarker(tag);

cacheHit

=

tag.equals("cache-hit");

}

@Override

protected

Response<TResponse>

parseNetworkResponse(NetworkResponse

response)

{

Gson

gson

=

new

Gson();

//無網(wǎng)絡(luò)時(shí),使用本地緩存,通過url去匹配緩存,volley

sdk是通過url創(chuàng)建不同的文件來實(shí)現(xiàn)緩存的

if

(!NetUtils.isConnect(mContext)

&&

mRequestQueue.getCache().get(mUrl)

!=

null)

{

String

json

=

new

String(mRequestQueue.getCache().get(mUrl).data);

Log.d(TAG,

"url=="

+

mUrl

+

",json"

+

json);

cb.fResponseCacheStatus

=

ResponseCacheStatus.StaleFromCache;

return

Response.success(gson.fromJson(json,

clazz),

parseCacheHeaders(response));

}

//數(shù)據(jù)是否有更新

try

{

if

(response.statusCode

==

304)

{

//服務(wù)端返回緩存數(shù)據(jù)

cb.fResponseCacheStatus

=

ResponseCacheStatus.NotModifiedFromServer;

}

else

if

(response.statusCode

==

200)

{

if

(cacheHit)

{

//使用本地緩存

cb.fResponseCacheStatus

=

ResponseCacheStatus.FreshFromCache;

}

else

{

//使用服務(wù)端更新數(shù)據(jù)

cb.fResponseCacheStatus

=

ResponseCacheStatus.NewFromServer;

}

}

else

{

cb.fResponseCacheStatus

=

ResponseCacheStatus.NewFromServer;

}

Log.d(TAG,

"fResponseCacheStatus

=

"

+

cb.fResponseCacheStatus);

String

json

=

new

String(response.data,

parseCharset(response.headers));

return

Response.success(gson.fromJson(json,

clazz),

parseCacheHeaders(response));

}

catch

(UnsupportedEncodingException

|

JsonSyntaxException

e)

{

return

Response.error(new

ParseError(e));

}

}

@Override

protected

void

deliverResponse(TResponse

response)

{

listener.onResponse(response);

}

@Override

protected

VolleyError

parseNetworkError(VolleyError

volleyError)

{

return

super.parseNetworkError(volleyError);

}

}3.上面只做了返回成功的處理方式,返回失敗時(shí)由NetCallback內(nèi)部統(tǒng)一處理:@UiThread

public

abstract

class

NetCallback<TResponse>

{

public

ResponseCacheStatus

fResponseCacheStatus

=

ResponseCacheStatus.NewFromServer;

private

String

TAG

=

this.getClass().getSimpleName();

public

boolean

enableAutomaticToastOnError

=

true;

public

NetCallback()

{

}

public

NetCallback(boolean

enableAutomaticToastOnError)

{

this.enableAutomaticToastOnError

=

enableAutomaticToastOnError;

}

public

abstract

void

OnSuccess(TResponse

result);

public

abstract

void

OnError(RestfulError

error);

public

void

OnNetworkOff()

{

//do

nothing

,use

it

according

to

requirement

}

public

Response.Listener<TResponse>

getSuccessListener()

{

return

new

Response.Listener<TResponse>()

{

@Override

public

void

onResponse(TResponse

result)

{

OnSuccess(result);

}

};

}

public

Response.ErrorListener

getErrorListener()

{

return

new

Response.ErrorListener()

{

@Override

public

void

onErrorResponse(VolleyError

volleyError)

{

if

(volleyError

instanceof

TimeoutError)

{

Log.e(TAG,

"networkResponse

==

null");

//volley

TimeoutError

OnError(new

RestfulError());

}

if

(volleyEworkResponse

!=

null)

{

int

statusCode

=

volleyEworkResponse.statusCode;

String

errorMessage

=

new

String(volleyEworkResponse.data);

switch

(statusCode)

{

case

401:

//post

a

Permission

authentication

failed

event

break;

default:

Log.d(TAG,

"errorMessage

="

+

errorMessage);

try

{

RestfulError

error

=

new

Gson().fromJson(errorMessage,

RestfulError.class);

if

(enableAutomaticToastOnError

&&

error.getCode()

!=

null)

{

//toast(error.ExceptionMessage);

//toast

it

in

main

thread

}

OnError(error);

}

catch

(Exception

e)

{

OnError(new

RestfulError());

Log.d(TAG,

"e

="

+

e.toString());

}

break;

}

}

}

};

}

}4.注意到?jīng)]有,在AuthenticatedRequestBase內(nèi)部有一個(gè)環(huán)境類YZ,主要負(fù)責(zé)獲取項(xiàng)目主程序中的context和請求隊(duì)列:public

class

YZ

implements

AppRequestQueue

{

private

static

final

int

DEFAULT_VOLLEY_CACHE_SIZE

=

100

*

1024

*

1024;

private

Context

context;

private

int

cacheSize;

private

YZ()

{

}

@Override

public

RequestQueue

getRequestQueue()

{

return

Volley.newRequestQueue(context,

cacheSize);

}

public

Context

getContext()

{

return

context;

}

private

static

class

SingletonHolder

{

private

static

YZ

instance

=

new

YZ();

}

public

static

YZ

getInstance()

{

return

SingletonHolder.instance;

}

/**

*

need

a

app

context

*

*

@param

appContext

*/

public

void

init(final

Context

appContext)

{

init(appContext,

DEFAULT_VOLLEY_CACHE_SIZE);

}

/**

*

@param

appContext

*

@param

cacheSize

*/

pub

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論