请求外部接口的两种方式|请求外部接口的两种方式,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);
文章图片
把第三方接口存到一个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;
}
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 基于微信小程序带后端ssm接口小区物业管理平台设计
- 2020-04-07vue中Axios的封装和API接口的管理
- 调取接口时报404错误(ID:16)
- CICC(脑机接口,科幻几近成真())
- https请求被提早撤回
- 分享!如何分分钟实现微信扫二维码调用外部浏览器打开指定页面的功能
- 遇到不正当请求怎么办
- 接口|axios接口报错-参数类型错误解决
- 使用Promise对微信小程序wx.request请求方法进行封装