Http請求工具java
<dependency> <groupId>cn.gjing</groupId> <artifactId>tools-httpclient</artifactId> <version>1.2.1</version> </dependency>
返回值類型最好與目標方法一致
,不然可能會出現轉換異常,在不確認返回類型時最好使用String
去接收。在請求結束後,能夠經過get()
方法獲取返回的內容,也能夠經過listener()
方法指定監聽者去監聽結果返回後的處理邏輯git
public class Test{ public static void main(String[] args) { String result = HttpClient.builder("http://127.0.0.1:8080/test", HttpMethod.GET, String.class) .execute() .get(); System.out.println(result); } }
public class Test{ public static void main(String[] args) { Map<String, String> map = new HashMap<>(16); map.put("head", "111"); HttpClient.builder("http://127.0.0.1:8080/test6", HttpMethod.GET, String.class) .header(map) .execute() .listener(System.out::println); } }
public class Test{ public static void main(String[] args) { Map<String, Object> param = new HashMap<>(); param.put("id","1"); HttpClient.builder("http://127.0.0.1:8080/test6", HttpMethod.GET, String.class) .param(param) .listener(System.out::println); } }
能夠是JSON字符串、Map、JSON對應實體對象,這裏演示經過map傳遞github
public class Test{ public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("key", "code"); map.put("val", "200"); Map resultMap = HttpClient.builder("http://127.0.0.1:8080/test6", HttpMethod.POST, Map.class) .body(map) .get(); } }
Url拼接, 返回結果格式如: http://xxx/param1/param2工具
public static void main(String[] args) { String url = "http://127.0.0.1:8080/"; Object[] param = {1, 2, 3, 4}; UrlUtil.urlAppend(url, param); }
參數按照字段名的Unicode碼從小到大排序(字典序), 獲得的結果格式如: a=參數1&b=參數2ui
public static void main(String[] args) { Map<String, Object> map = new HashMap<>(16); map.put("a", "參數1"); map.put("b", "參數2"); UrlUtil.paramUnicodeSort(map, false, false); }
參數說明編碼
參數 | 描述 |
---|---|
paramMap | 參數 |
urlEncode | 是否進行URL編碼 |
keyToLower | 轉換後的參數的key值是否要轉爲小寫 |
將URL地址後帶的參數轉成mapurl
public static void main(String[] args) { String url = "http://127.0.0.1:8080?a=2&b=2"; UrlUtil.toMap(url); }
項目源代碼可前往GitHUb查看:tools-httpclientcode