Reputation: 1093
Spoiled by Python (e.g. requests.post(url, data={'p1':'v1','p2':'v2'}, headers={'H1': 'V1'})
), I am looking for an equivalent to use on Android.
My code is already run on separate Threads, so I don't need AsyncWhatever.
HttpURLConnection is recommended for Android because it is all kinds of lightweight, but the equivalent of the Python request is... large.
I see multiple partial (e.g. pre-encoded params string) solutions, and several problems to work around. Rather than risk mistakes or overlooking something writing it myself, I ask:
Is such a wrapper available already, a request(Method, String, Map<String,String>, Map<String,String>)
, or similar?
I expect such a solution to need little code per call, and manage all weirdness (e.g. pre-Froyo keepAlive hack) itself.
Upvotes: 1
Views: 841
Reputation: 13007
I suppose I have the right solution for you. Had the same problem (spoiled by Node.js request) and didn't like the "interface" of HttpURLConnection
.
You can find a tiny library without dependencies which wrappes HttpURLConnection
in a way that not so common use cases can be implemented by using the wrapped HUC. It's called DavidWebb. There is also a link to alternative libraries in case you miss something.
A typical POST request with JSON payload and JSON response with some headers would look like this:
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 are many ways to set default values for the Webb
instance and use or overwrite them in the Request
object.
The library is well tested, especially on Android, but it has no specific code or dependencies on Android API, so you have to manage keepAlive
for Froyo by yourself.
Upvotes: 1