Monday, 15 September 2014

android - HTTP request wraper (method, headers, parameters) for HttpURLConnection? -



android - HTTP request wraper (method, headers, parameters) for HttpURLConnection? -

spoiled python (e.g. requests.post(url, data={'p1':'v1','p2':'v2'}, headers={'h1': 'v1'})), looking equivalent utilize on android.

my code run on separate threads, don't need asyncwhatever.

httpurlconnection recommended android because kinds of lightweight, equivalent of python request is... large. see multiple partial (e.g. pre-encoded params string) solutions, , several problems work around. rather risk mistakes or overlooking writing myself, ask: such wrapper available already, request(method, string, map<string,string>, map<string,string>), or similar?

i expect such solution need little code per call, , manage weirdness (e.g. pre-froyo keepalive hack) itself.

i suppose have right solution you. had same problem (spoiled node.js request) , didn't "interface" of httpurlconnection.

you can find tiny library without dependencies wrappes httpurlconnection in way not mutual utilize cases can implemented using wrapped huc. it's called davidwebb. there link alternative libraries in case miss something.

a typical post request json payload , json response headers this:

class="lang-java prettyprint-override">jsonobject postobj = new jsonobject(); postobj.put("p1", "v1"); postobj.put("p2", "v2"); webb webb = webb.create(); response<jsonobject> response = webb .post("http://www.example.com/app/myresource") .header("x-date-header", new date()) .header("x-other-header", "some-text") .body(postobj) .connecttimeout(3000) .asjsonobject(); if (response.issuccess()) { jsonobject outcome = response.getbody(); // ... } else { system.out.println(response.getstatuscode()); system.out.println(response.getresponsemessage()); system.out.println(response.geterrorbody()); }

there many ways set default values webb instance , utilize or overwrite them in request object.

the library tested, on android, has no specific code or dependencies on android api, have manage keepalive froyo yourself.

android post httpurlconnection

No comments:

Post a Comment