×

深圳网站建设—APP开发—网站制作—小程序开发_博纳网络公司

0755 -
82538016
82560826
网站制作资讯

开发APP关于Volley库支持的HTTP方法与代码分享

文章编辑:网站建设 文章来源:APP开发 浏览量:

  APP开发关于Volley网络库简介,深圳APP开发公司提醒Volley网络库Volley库是Google官方提供的开源网络库,在Android系统中也使用了这个网络库。Volley库对网络功能进行了封装,默认根据Android系统的不同版本使用不同的HTTP协议栈。
  在Android2.3及以上版本使用HurlStack协议栈,在Android2.3以下版本使用HttpClientStack协议栈。使用者也可以自己设置其中使用的HTTP协议栈,使用比较灵活。Volley库支持字符串、图片和JSON格式数据的处理,但因为在解析服务器端的响应消息时,Volley库是把响应消息存储在内存中,所以Volley库不适合大数据量的网络请求,如下载大文件等。在Volley库的Volley类中,提供了设置请求HTTP协议栈的方法。
publicclassVolley{  /**Defaulton-diskcachedirectory.*/  privatestaticfinalStringDEFAULT_CACHE_DIR="volley";  /**  *Createsadefaultinstanceoftheworkerpoolandcalls{@linkRequestQueue#start()}onit.  *  *@paramcontextA{@linkContext}touseforcreatingthecachedir.  *@paramstackAn{@linkHttpStack}touseforthenetwork,ornullfordefault.  *@returnAstarted{@linkRequestQueue}instance.  */  publicstaticRequestQueuenewRequestQueue(Contextcontext,HttpStackstack){    FilecacheDir=newFile(context.getCacheDir(),DEFAULT_CACHE_DIR);    StringuserAgent="volley/0";    try{      StringpackageName=context.getPackageName();
  PackageInfoinfo=context.getPackageManager().getPackageInfo      (packageName,0);userAgent=packageName+"/"+info.versionCode;    }catch(NameNotFoundExceptione){    }    if(stack==null){       if(Build.VERSION.SDK_INT>=9){         stack=newHurlStack();       }else{         //PriortoGingerbread,HttpUrlConnectionwasunreliable.         //See:http://android-developers.blogspot.com/2011/09/androids-http-clients.html         stack=newHttpClientStack(AndroidHttpClient.newInstance(userAgent));       }    }    Networknetwork=newBasicNetwork(stack);    RequestQueuequeue=newRequestQueue(newDiskBasedCache(cacheDir),network);    queue.start();
 returnqueue;  }  /**  *Createsadefaultinstanceoftheworkerpoolandcalls{@linkRequestQueue#start()}onit.  *  *@paramcontextA{@linkContext}touseforcreatingthecachedir.  *@returnAstarted{@linkRequestQueue}instance.  */  publicstaticRequestQueuenewRequestQueue(Contextcontext){    returnnewRequestQueue(context,null);  }}在Volley库的Request类中,定义了Volley库支持的HTTP方法。publicabstractclassRequest<T>implementsComparable<Request<T>>{  …  /**  *Supportedrequestmethods.  */
  publicinterfaceMethod{    intDEPRECATED_GET_OR_POST=-1;    intGET=0;    intPOST=1;    intPUT=2;    intDELETE=3;    intHEAD=4;    intOPTIONS=5;    intTRACE=6;    intPATCH=7;  }…  publicRequest(intmethod,Stringurl,Response.ErrorListenerlistener){    mMethod=method;    mUrl=url;    mIdentifier=createIdentifier(method,url);    mErrorListener=listener;    setRetryPolicy(newDefaultRetryPolicy());    mDefaultTrafficStatsTag=findDefaultTrafficStatsTag(url);  }…}
在Volley库中,HttpHeaderParser类用于处理从服务器获得的头字段数据。publicclassHttpHeaderParser{    publicstaticCache.EntryparseCacheHeaders(NetworkResponseresponse){    longnow=System.currentTimeMillis();    Map<String,String>headers=response.headers;    longserverDate=0;    longlastModified=0;    longserverExpires=0;    longsoftExpire=0;    longfinalExpire=0;    longmaxAge=0;    longstaleWhileRevalidate=0;    booleanhasCacheControl=false;    booleanmustRevalidate=false;    StringserverEtag=null;    StringheaderValue;
 headerValue=headers.get("Date");    if(headerValue!=null){       serverDate=parseDateAsEpoch(headerValue);    }    headerValue=headers.get("Cache-Control");    if(headerValue!=null){       hasCacheControl=true;       String[]tokens=headerValue.split(",");       for(inti=0;i<tokens.length;i++){          Stringtoken=tokens[i].trim();          if(token.equals("no-cache")||token.equals("no-store")){            returnnull;          }elseif(token.startsWith("max-age=")){            try{              maxAge=Long.parseLong(token.substring(8));            }catch(Exceptione){            }          }elseif(token.startsWith("stale-while-revalidate=")){            try{              staleWhileRevalidate=Long.parseLong(token.substring(23));            }catch(Exceptione){
  }         }elseif(token.equals("must-revalidate")||token.equals("proxy-revalidate")){            mustRevalidate=true;          }       }    }    headerValue=headers.get("Expires");    if(headerValue!=null){      serverExpires=parseDateAsEpoch(headerValue);    }    headerValue=headers.get("Last-Modified");    if(headerValue!=null){      lastModified=parseDateAsEpoch(headerValue);    }    serverEtag=headers.get("ETag");    //Cache-ControltakesprecedenceoveranExpiresheader,evenifbothexistandExpires    //ismorerestrictive.    if(hasCacheControl){      softExpire=now+maxAge*1000;
finalExpire=mustRevalidate          ?softExpire          :softExpire+staleWhileRevalidate*1000;    }elseif(serverDate>0&&serverExpires>=serverDate){      //DefaultsemanticforExpireheaderinHTTPspecificationissoftExpire.      softExpire=now+(serverExpires-serverDate);      finalExpire=softExpire;    }    Cache.Entryentry=newCache.Entry();    entry.data=response.data;    entry.etag=serverEtag;    entry.softTtl=softExpire;    entry.ttl=finalExpire;    entry.serverDate=serverDate;    entry.lastModified=lastModified;    entry.responseHeaders=headers;    returnentry;  }…}
目前大多数APP与服务器间传输数据时,都是使用JSON格式,Volley库中提供了使用JSON格式传递数据的类。publicabstractclassJsonRequest<T>extendsRequest{/**DefaultcharsetforJSONrequest.*/protectedstaticfinalStringPROTOCOL_CHARSET="utf-8";/**Contenttypeforrequest.*/privatestaticfinalStringPROTOCOL_CONTENT_TYPE=String.format("application/json;charset=%s",PROTOCOL_CHARSET);privatefinalListener<T>mListener;privatefinalStringmRequestBody;  /**  *DeprecatedconstructorforaJsonRequestwhichdefaultstoGETunless{@link#getPostBody()}  *or{@link#getPostParams()}isoverridden(whichdefaultstoPOST).  *  *@deprecatedUse{@link#JsonRequest(int,String,String,Listener,ErrorListener)}.  */
 publicJsonRequest(Stringurl,StringrequestBody,Listener<T>listener,      ErrorListenererrorListener){    this(Method.DEPRECATED_GET_OR_POST,url,requestBody,listener,errorListener);  }  publicJsonRequest(intmethod,Stringurl,StringrequestBody,Listener<T>listener,      ErrorListenererrorListener){    super(method,url,errorListener);    mListener=listener;    mRequestBody=requestBody;  }  @Override  protectedvoiddeliverResponse(Tresponse){    mListener.onResponse(response);  }  @Override  abstractprotectedResponse<T>parseNetworkResponse(NetworkResponseresponse);  /**
*@deprecatedUse{@link#getBodyContentType()}.  */  @Override  publicStringgetPostBodyContentType(){    returngetBodyContentType();  }  /**  *@deprecatedUse{@link#getBody()}.  */  @Override  publicbyte[]getPostBody(){    returngetBody();  }  @Override  publicStringgetBodyContentType(){    returnPROTOCOL_CONTENT_TYPE;  }  @Override  publicbyte[]getBody(){    try{      returnmRequestBody==null?null:mRequestBody.getBytes(PROTOCOL_CHARSET);
 }catch(UnsupportedEncodingExceptionuee){      VolleyLog.wtf("UnsupportedEncodingwhiletryingtogetthebytesof%susing%s",          mRequestBody,PROTOCOL_CHARSET);      returnnull;    }  }}publicclassJsonObjectRequestextendsJsonRequest<JSONObject>{  /**  *Createsanewrequest.  *@parammethodtheHTTPmethodtouse  *@paramurlURLtofetchtheJSONfrom  *@paramjsonRequestA{@linkJSONObject}topostwiththerequest.Nullisallowedand  * indicatesnoparameterswillbepostedalongwithrequest.  *@paramlistenerListenertoreceivetheJSONresponse  *@paramerrorListenerErrorlistener,ornulltoignoreerrors.  */  publicJsonObjectRequest(intmethod,Stringurl,JSONObjectjsonRequest,      Listener<JSONObject>listener,ErrorListenererrorListener)
errorListener){    super(method,url,(jsonRequest==null)?null:jsonRequest.toString(),listener,          errorListener);  }  /**  *Constructorwhichdefaultsto<code>GET</code>if<code>jsonRequest</code>is  *<code>null</code>,<code>POST</code>otherwise.  *  *@see#JsonObjectRequest(int,String,JSONObject,Listener,ErrorListener)  */  publicJsonObjectRequest(Stringurl,JSONObjectjsonRequest,Listener<JSONObject>listener,      ErrorListenererrorListener){    this(jsonRequest==null?Method.GET:Method.POST,url,jsonRequest,        listener,errorListener);  }  @Override  protectedResponse<JSONObject>parseNetworkResponse(NetworkResponseresponse){
 try{      StringjsonString=newString(response.data,          HttpHeaderParser.parseCharset(response.headers,PROTOCOL_CHARSET));      returnResponse.success(newJSONObject(jsonString),          HttpHeaderParser.parseCacheHeaders(response));    }catch(UnsupportedEncodingExceptione){      returnResponse.error(newParseError(e));    }catch(JSONExceptionje){      returnResponse.error(newParseError(je));    }  }}
好了,APP开发公司本文关于“开发APP关于Volley库支持的HTTP方法与代码分享”就到这里,谢谢关注,希望能给您的APP开发前期工作有所帮助,博纳网络编辑整理。

当前文章链接:/construction/appkaifa/2342.html
如果您觉得案例还不错请帮忙分享:

[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【qin@198bona.com 】,我们在确认后,会立即删除,保证您的版权。