Java使用公开接口
一直以来,我们开发都是后端写接口,前端调用接口。
但是当你的数据是从其他接口而来的,你的后端只是作为数据的逻辑处理用的话,那么你就必须懂得一种后端自己调用接口的方式。
<!--首先是必要的依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
这里以POST请求为例子
/**
* 发送POST请求
* @param url
* @param data
* @return
*/
public static String sendPost(String url, String data) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);//决定使用Post
StringEntity stringentity = new StringEntity(data,
ContentType.create("text/json", "ISO_8859_1"));
//StringEntity的字符编码是ISO_8859_1,不能一开始就用utf-8,不然都会乱码。
//stringentity.setContentType("UTF-8");
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);
response = EntityUtils
.toString(httpresponse.getEntity());
response=new String(response.getBytes("ISO-8859-1"),"utf-8");
} finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
到了这一步只能说只完成了一半。
因为你需要自己构建JSON格式。
//简单构建,以Map<key,value>形式
//若JSON格式复杂,可以使用Map<key,Object>的形式构建,其中有集合有数组。
map.put("key",list);
String Json=JSONObject.toJSONString(Map)
//
JSONObject jsonObject = JSONArray.parseObject(str);
调用接口
//获得字符串类型的JSON信息
String str= IotParkUtils.sendPost("http://XXX.XXX.XXX.XXX:XX/XXXX", Json).trim();
//获得JSON格式的信息
JSONObject jsonObject = JSONArray.parseObject(str);
//两种获得JSON中的信息的简单方式
JSONObject json =jsonObject.get("key")
String json = jsonObject.getString("key");
//之后就可以存入数据库了