HttpRequest,HTTP的请求利器

项目地址: https://github.com/kevinsawicki/http-request

1、发送一个get请求,获取响应码,够方便了吧。
int code = HttpRequest.get("http://google.com").code();
2、加个请求参数呢?可以直接加在get方法里,选择是否进行编码,不习惯的还可以用Map传参哦。
HttpRequest request = HttpRequest.get("http://google.com", true, 'q', "baseball gloves", "size", 100);
3、发一个带文件的POST请求
HttpRequest request = HttpRequest.post("url”);
request.header("Content-Type", "multipart/form-data;boundary=AaB03x");
request.part("imagefile", "test.log", "image/jpeg", new File("d:/test/test.jpg"));
4、再发一个带Form的POST
        Map<String, String> data = new HashMap<String, String>();
        data.put("user", "A User");
        data.put("state", "CA");
        HttpRequest request = HttpRequest.post(url).form(data);
5、发送带JSON的POST

        JsonObject jsonContent = new JsonObject();

        jsonContent.addProperty("content", msgBody);

 

        JsonObject jsonData = new JsonObject();

        jsonData.add("data", jsonContent);

        jsonData.addProperty("subtype", subType);

 

HttpRequest httpRequest = HttpRequest.post(url).acceptJson();

        httpRequest.send(jsonData.toString());

 

        int code = httpRequest.code();

        String body = httpRequest.body();

 

这个开源实现,最大的特点是基于URLConnection实现,不依赖HttpClient。
整个项目的实现只有一个Java类文件,有兴趣的可以自己看哦。

posted @ 2015-05-27 10:35  vikey.z  阅读(15632)  评论(0编辑  收藏  举报