请求外部接口的两种方式|请求外部接口的两种方式,get请求和post请求.

1.Get请求 可以封装成工具类,代码如下,我这里工具类名叫UrlTools,方法名叫getStringByUrl(List urlList); 参数传入一个list集合.集合中存放接口地址.

//get请求外部接口 public String getStringByUrl(List urlList){for (int i = 0; i < urlList.size(); i++) { InputStream in = null; InputStreamReader isr = null; BufferedReader br = null; try { URL url = new URL(urlList.get(i)); URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); in = conn.getInputStream(); isr = new InputStreamReader(in); br = new BufferedReader(isr); String line = ""; StringBuilder content = new StringBuilder(); while ((line = br.readLine()) != null) { content.append(line); } /*logger.info(" 接口访问成功 - " + urlList.get(i)); logger.info("content的结果: "+content.toString()); */ return content.toString().trim(); } catch (Exception e) { logger.error(" ** 接口访问失败 - "+urlList.get(i) +"\r\n 错误信息:" + e.getClass()+" - "+e.getMessage()); } finally { if (null != br) { try { br.close(); } catch (IOException e) { } }if (null != isr) { try { isr.close(); } catch (IOException e) { } }if (null != in) { try { in.close(); } catch (IOException e) { } } } } return null; }

2.get请求使用方法
ArrayList schooldetatils = new ArrayList<>(); schooldetatils.add("https://xcx.wanxue.cn/hwkycp/public/api/getSchoolDetail?code="+code); String stringByUrl = UrlTools.INSTANCE.getStringByUrl(schooldetatils); JSONObject stringByUrlObj = JSONObject.parseObject(stringByUrl);

请求外部接口的两种方式|请求外部接口的两种方式,get请求和post请求.
文章图片

把第三方接口存到一个list集合里,调用工具类UrlTools中的方法时,传入接口地址,因为我这里返回的数据格式是json,所以转成了json格式进行处理,使用开发工具IDEA的debug功能,打断点可以看到接口中返回的数据.
3.发送post请求 【请求外部接口的两种方式|请求外部接口的两种方式,get请求和post请求.】代码如下:
private static String sendPostJsonStr(String url, String jsonString) throws IOException { String resp = ""; StringEntity entityStr = new StringEntity(jsonString, ContentType.create("text/plain", "UTF-8")); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entityStr); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); resp = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (ClientProtocolException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } finally { if (response != null) { try { response.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } if (resp == null || resp.equals("")) { return ""; } return resp; }

    推荐阅读