LiteHttp是一款简单、智能、灵活的HTTP框架库,它在请求和响应层面做到了全自动构建和解析,主要用于Android快速开发。借助LiteHttp你只需要一行代码即可完美实现http连接,它全面支持GET, POST, PUT, DELETE, HEAD, TRACE, OPTIONS 和 PATCH八种基本类型。LiteHttp能将Java Model转化为http请求参数,也能将响应的json语句智能转化为Java Model,这种全自动解析策略将节省你大量的构建请求、解析响应的时间。并且,你能自己继承重新实现Dataparser这个抽象类并设置给Request,来将http原始的inputstream转化为任何你想要的东西。
http://litesuits.github.io/guide/http/get-start.html
LiteHttp引言,一个案例告诉你它的强大之处。
开源中国项目地址:http://www.oschina.net/p/android-lite-http
LiteHttpClient client = LiteHttpClient.getInstance(context); Response res = client.execute(new Request("http://baidu.com")); String html = res.getString();
HttpAsyncExcutor asyncExcutor = new HttpAsyncExcutor(); asyncExcutor.execute(client, new Request(url), new HttpResponseHandler() { @Override protected void onSuccess(Response res, HttpStatus status, NameValuePair[] headers) { // do some thing on UI thread } @Override protected void onFailure(Response res, HttpException e) { // do some thing on UI thread } });
// build a request url as : http://a.com?name=jame&id=18 Man man = new Man("jame",18); Response resonse = client.execute(new Request("http://a.com",man));
man class:
public class Man implements HttpParam{ private String name; private int id; private int age; public Man(String name, int id){ this.name = name; this.id= id; } }
String url = "http://litesuits.github.io/mockdata/user?id=18"; User man = client.get(url, null, User.class);
User Class:
public class User extends ApiResult { //全部声明public是因为写sample方便,不过这样性能也好, //即使private变量LiteHttp也能自动赋值,开发者可自行斟酌修饰符。 public UserInfo data; public static class UserInfo { public String name; public int age; public ArrayList<String> girl_friends; } } public abstract class ApiResult { public String api; public String v; public Result result; public static class Result { public int code; public String message; } }
User JSON Structure:
{ "api": "com.xx.get.userinfo", "v": "1.0", "result": { "code": 200, "message": "success" }, "data": { "age": 18, "name": "qingtianzhu", "girl_friends": [ "xiaoli", "fengjie", "lucy" ] } }
String url = "http://192.168.2.108:8080/LiteHttpServer/ReceiveFile"; FileInputStream fis = new FileInputStream(new File("sdcard/1.jpg")); Request req = new Request(url); req.setMethod(HttpMethod.Post) .setParamModel(new BaiDuSearch()) .addParam("lite", new File("sdcard/lite.jpg"), "image/jpeg") .addParam("feiq", new File("sdcard/feiq.exe"), "application/octet-stream"); if (fis != null) req.addParam("meinv", fis, "sm.jpg", "image/jpeg"); Response res = client.execute(req);
// one way File file = client.execute(imageUrl, new FileParser("sdcard/lite.jpg"), HttpMethod.Get); // other way Response res = client.execute(new Request(imageUrl).setDataParser(new BitmapParser())); Bitmap bitmap = res.getBitmap();