Packagecom.create.qdocumentimtest.rxjavatest;ImportCom.squareup.okhttp.Callback;ImportCom.squareup.okhttp.FormEncodingBuilder;Importcom.squareup.okhttp.OkHttpClient;Importcom.squareup.okhttp.Request;ImportCom.squareup.okhttp.RequestBody;ImportCom.squareup.okhttp.Response;Importjava.io.IOException;ImportJava.util.HashMap;Importjava.util.Objects;/*** Created by Administrator on 2016/6/7 0007.*/ Public classhttphelper {String baseUrl= ""; PrivateOkhttpclient okhttp =Newokhttpclient (); PrivateString URL; Publichttphelper (String url) { This. url =URL; } /*** GET Request Synchronization method * *@return */ PublicString Requestbygetsync () {Request Request=Newrequest.builder (). URL (URL). build (); Try{Response Response= Okhttp.newcall (Request). Execute ();//Sync Request if(!response.issuccessful ()) { Throw NewIOException ("Unexpected Code" +response); } returnresponse.body (). String (); } Catch(IOException e) {e.printstacktrace (); } return NULL; } /*** GET Request Async * *@paramCallback *@return */ Public voidRequestbygetasync (Callback Callback) {Request Request=Newrequest.builder (). URL (URL). build (); Okhttp.newcall (Request). Equals (callback); } /*** Post Async * *@paramCallback*/ Public voidRequestbypostasync (hashmap<string, objects>map, Callback Callback) {Formencodingbuilder Formencodingbuilder=NewFormencodingbuilder (); for(String key:map.keySet ()) {Formencodingbuilder.add (key, Map.get (key)+ ""); } Requestbody Body=Formencodingbuilder.build (); Request Request=Newrequest.builder (). URL (baseUrl+URL). Post (body). Build (); Okhttp.newcall (Request). Enqueue (callback); } /*** Post Sync request *@paramMap *@return */ PublicString Requestbypostsync (hashmap<string, objects>map) {Formencodingbuilder Formencodingbuilder=NewFormencodingbuilder (); for(String key:map.keySet ()) {Formencodingbuilder.add (key, Map.get (key)+ ""); } Requestbody Body=Formencodingbuilder.build (); Request Request=Newrequest.builder (). URL (URL). Post (body). Build (); Response Response=NULL; Try{Response=Okhttp.newcall (Request). Execute (); if(Response.issuccessful ()) {returnresponse.body (). String (); } Else { Throw NewIOException ("Unexpected Code" +response); } } Catch(IOException e) {e.printstacktrace (); } return NULL; }}
Self-encapsulated Okhttp request