码迷,mamicode.com
首页 > 编程语言 > 详细

Java中使用HTTP阻塞式调用服务器API

时间:2018-12-22 18:24:39      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:als   out   取数据   exce   string   red   prope   tac   方式   

应用场景:前端页面点击刷新,调用服务器A上Java接口,然后A调用服务器B的后台Python接口实时刷新后台数据库。

 

在这个场景中会涉及到两个问题:异步,Python服务器压力

 

(一)解决Python服务器压力

如果Python服务器接口不做任何措施,那么可能会有恶意的访问,从而导致该服务器一直刷新后台数据库。

我的解决方式是:服务器B会提供一串字符串给服务器A,当服务器A调用服务器B的服务时,将传递的参数和该字符串拼接再进行MD5加密,从而在服务器B上通过这个token值明确对方身份。

 

(二)异步

异步问题是:如何解决服务器A上的Java接口等待Python程序刷新数据库后返回的success,从而使得前端页面阻塞更新。

主要是通过Java中HttpURLConnection.InputStreamReader的方法实现异步:

    public String requestRefresh(String token, String clusterName){
        String result = null;
        try{
            // 打开和URL之间的连接
            URL url = new URL(URL_Refresh_Couchbase_Cluster);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            // 把数据写入请求的Body
            out.write("token=" + token + "&cluster=" + clusterName); //参数形式跟在地址栏的一样
            out.flush();
            out.close();
            // 获取数据,将返回的输入流转换成字符串
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            result = bufferedReader.readLine();
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
        }catch (Exception e){
            log.info("(requestRefresh) sending GET Request to refresh mysql databse has exception : {}", e);
            e.printStackTrace();
        }
        return result;
    }

 

Java中使用HTTP阻塞式调用服务器API

标签:als   out   取数据   exce   string   red   prope   tac   方式   

原文地址:https://www.cnblogs.com/jayinnn/p/10161828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!