java中调用api的方式(postJsonHTTP)


//设置格式以及字符编码
 private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 
 /**
    * @Description: 获取抓拍机列表
    * @param boxIP   调用服务器的ip地址
    * @param port    调用服务器的端口号
    * @param jsonStr  发送的数据
    * @param requestHead  请求头
    * @return:
    * @Author: liujianhua
    * @Date: 18:47
    */
 //比如:http://192.168.88.133:8080/api/selectById
 //同:http://boxIP:port/requestHead
 public static  String postJsonHTTP(String boxIP,String port ,String jsonStr,String requestHead) throws IOException {
        String url = "http://"+boxIP+":"+port+"/"+requestHead;
        OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS).build();
        RequestBody requestBody = RequestBody.create(JSON, jsonStr);
        Request.Builder builder = new Request.Builder();
        final Request request = builder.url(url).post(requestBody).build();
        final Call call = okHttpClient.newCall(request);
        Response response;
        response = call.execute();
        return response.body().string();
    }
如何调用
 public List<Map> requestCameraList() throws Exception{
        String boxIP = "192.168.88.133";
        String port = "8080";
        //将数据存放到map中
        Map requestMap = new HashMap();
        requestMap.put("Name","SubDevicesManageRequest");
        //下面将map转为json  
        String ret = postJsonHTTP(boxIP, port, gson.toJson(requestMap),LOADBAIDUCAMERA);
        //将收到的数据转为map格式
        HashMap retMap = gson.fromJson(ret, HashMap.class);
        System.err.println(retMap);
        return cameraListMap;
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想养一只!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值