一、添加依赖
hutool依赖,junit依赖
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.4.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
二、get和post参数请求方式
/** * 请求地址 * https://my.fengniao.com/info.php?userid=604583 */ @Test public void testGetParam() { HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("userid", "604583"); String result = HttpUtil.get("https://my.fengniao.com/info.php", paramMap); System.out.println(result); } /** * 请求地址 * https://ug.baidu.com/mcp/pc/pcsearch * 参数格式 * {"invoke_info":{"pos_1":[{}],"pos_2":[{}],"pos_3":[{}]}} * 响应如下 * {"errno":0,"errmsg":"ok","data":{"log_id":"89413141308091000","action_rule":{"pos_1":[],"pos_2":[],"pos_3":[]}}} */ @Test public void testPostParam() { String body = "{\"invoke_info\":{\"pos_1\":[{}],\"pos_2\":[{}],\"pos_3\":[{}]}}"; String result = HttpUtil.post("https://ug.baidu.com/mcp/pc/pcsearch", body); System.out.println(result); } /** * 自定义header的方式请求方法 * * @throws Exception */ @Test public void testHttps() throws Exception { String json = "{\"invoke_info\":{\"pos_1\":[{}],\"pos_2\":[{}],\"pos_3\":[{}]}}"; String result = HttpRequest.post("https://ug.baidu.com/mcp/pc/pcsearch") .header("Content-Type", "application/json") //.setHttpProxy("127.0.0.1", 9080) //配置代理 .body(json) .execute().body(); System.out.println(result); }