項目地址: 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類文件,有興趣的可以自己看哦。