pom文件
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency>
get方法
@RequestMapping("redirect") @ResponseBody public JSONObject getRedirectUrl(HttpServletRequest request, String path) throws UnsupportedEncodingException { if (!path.startsWith("\\d")) { path = "http://localhost:8080/" + path; } else { path = "http://" + path; } // 获取参数 Map<String, String[]> parameterMap = request.getParameterMap(); Set<Entry<String, String[]>> entrySet = parameterMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { if (!"path".equals(entry.getKey())) { if (StringUtils.isNotBlank(entry.getValue()[0])) { path += entry.getKey() + "=" + URLEncoder.encode(entry.getValue()[0], "utf-8") + "&"; } } } JSONObject json = null; // 1.使用默认的配置的httpclient CloseableHttpClient client = HttpClients.createDefault(); // 2.使用get方法 HttpGet httpGet = new HttpGet(path); CloseableHttpResponse response = null; try { // 3.执行请求,获取响应 response = client.execute(httpGet); // 看请求是否成功,这儿打印的是http状态码 System.out.println(response.getStatusLine().getStatusCode()); // 4.获取响应的实体内容,就是我们所要抓取得网页内容 HttpEntity entity = response.getEntity(); // 5.将其打印到控制台上面 // 方法一:使用EntityUtils if (entity != null) { String json_String = EntityUtils.toString(entity, "utf-8"); // System.out.println(json_String); json = JSONObject.parseObject(json_String); } EntityUtils.consume(entity); } catch (Exception e) { e.printStackTrace(); } return json; }
post方法点击打开链接