This is a util class I used.
1 Public classHttpbaseservice {2 3 PrivateOkhttpclient client =Newokhttpclient ();4 Private StaticFinal mediatype JSON = Mediatype.parse ("Application/json; Charset=utf-8");5 Publicstring sendgetrequest (string url) {6Request Request =Newrequest.builder (). URL (URL). build ();7Response Response =NULL;8 Try {9Response =Client.newcall (Request). Execute ();Ten if(Response.issuccessful ()) { One returnResponse.body ().string(); A } -}Catch(IOException e) { - e.printstacktrace (); the } - return ""; - } - + Public intsenddelrequest (String url) { -Request Request =Newrequest.builder (). URL (url). Delete (). build (); + returnsendoperaterequest (request); A } at - Public intsendpostrequest (String url,string json) { - //requestbody formbody = new Formencodingbuilder () - //. Add ("Platform", "Android") - //. Add ("name", "Bug") - //. Add ("Subject", "xxxxxxxxxxxxxxx") in //. Build (); -Requestbody BODY =requestbody.create (Json,json); toRequest Request =Newrequest.builder (). URL (URL). Post (body). Build (); + returnsendoperaterequest (request); - } the Public intsendputrequest (String url,string json) { *Requestbody BODY =requestbody.create (Json,json); $Request Request =Newrequest.builder (). URL (URL). put (body). Build ();Panax Notoginseng returnsendoperaterequest (request); - } the + Private intsendoperaterequest (Request request) { AResponse Response =NULL; the Try { +Response =Client.newcall (Request). Execute (); - if(Response.issuccessful ()) { $ return 0; $ } -}Catch(IOException e) { - e.printstacktrace (); the } - return-1;Wuyi } the}
Okhttp Common methods Examples