Java后端使用公开接口

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");
//之后就可以存入数据库了
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值