你的位置:首页 > 软件开发 > Java > java web api接口调用

java web api接口调用

发布时间:2017-08-17 10:00:18
Web Services 被W3C进行了标准化定义。Web Services 发布到网上,可以公布到某个全局注册表,自动提供服务URL,服务描述、接口调用要求、参数说明以及返回值说明。比如中国气象局可以发布天气预报服务。所有其它网站或手机App如果需要集成天气预报功能,都可以访问 ...

Web Services 被W3C进行了标准化定义。

Web Services 发布到网上,可以公布到某个全局注册表,自动提供服务URL,服务描述、接口调用要求、参数说明以及返回值说明。比如中国气象局可以发布天气预报服务。所有其它网站或手机App如果需要集成天气预报功能,都可以访问该Web Service获取数据。

Web Services 主要设计目标是提供公共服务。

Web Services 全部基于Web Services 还有标准的身份验证方式(非公共服务时验证使用者身份)。

轻量化的Web API

公司内部使用的私有服务,我们知道它的接口Url,因此不需要自动发现它。我们有它的服务接口文档,因此也不需要自动描述和自动调用。
即使Web Services的特性(自动发现、自动学会调用方式)很美好,但私有服务往往不需要这些。

Web API一般基于HTTP/REST来实现,什么都不需要定义,参数(输入的数据)可以是JSON,

获取远程数据的方式正在从Web Services向Web API转变。

Web Services的架构要比Web API臃肿得多,它的每个请求都需要封装成

  

 

  /**
     * 根据指定url,编码获得字符串
     *
     * @param address
     * @param Charset
     * @return
     */
    public static String getStringByConAndCharset(String address, String Charset) {

        StringBuffer sb;
        try {
            URL url = new URL(address);

            URLConnection con = url.openConnection();
            BufferedReader bw = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset));
            String line;
            sb = new StringBuffer();
            while ((line = bw.readLine()) != null) {
                sb.append(line + "\n");
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
            sb = new StringBuffer();
        }

        return sb.toString();
    }

    /**
     * 通过post方式获取页面源码
     *
     * @param urlString
     *            url地址
     * @param paramContent
     *            需要post的参数
     * @param chartSet
     *            字符编码(默认为ISO-8859-1)
     * @return
     * @throws IOException
     */
    public static String postUrl(String urlString, String paramContent, String chartSet, String contentType) {
        long beginTime = System.currentTimeMillis();
        if (chartSet == null || "".equals(chartSet)) {
            chartSet = "ISO-8859-1";
        }

        StringBuffer result = new StringBuffer();
        BufferedReader in = null;

        try {
            URL url = new URL((urlString));
            URLConnection con = url.openConnection();

            // 设置链接超时
            con.setConnectTimeout(3000);
            // 设置读取超时
            con.setReadTimeout(3000);
            // 设置参数
            con.setDoOutput(true);
            if (contentType != null && !"".equals(contentType)) {
                con.setRequestProperty("Content-type", contentType);
            }

            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), chartSet);
            writer.write(paramContent);
            writer.flush();
            writer.close();
            in = new BufferedReader(new InputStreamReader(con.getInputStream(), chartSet));
            String line = null;
            while ((line = in.readLine()) != null) {
                result.append(line + "\r\n");
            }
            in.close();
        } catch (MalformedURLException e) {
            logger.error("Unable to connect to URL: " + urlString, e);
        } catch (SocketTimeoutException e) {
            logger.error("Timeout Exception when connecting to URL: " + urlString, e);
        } catch (IOException e) {
            logger.error("IOException when connecting to URL: " + urlString, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {
                    logger.error("Exception throws at finally close reader when connecting to URL: " + urlString, ex);
                }
            }
            long endTime = System.currentTimeMillis();
            logger.info("post用时:" + (endTime - beginTime) + "ms");
        }
        return result.toString();
    }

    /**
     * 发送https请求
     * @param requestUrl  请求地址
     * @param requestMethod  请求方式(GET、POST)
     * @param outputStr  提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
        JSONObject json = null;
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(ssf);

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // 设置请求方式(GET/POST)
        conn.setRequestMethod(requestMethod);

        // 当outputStr不为null时向输出流写数据
        if (null != outputStr) {
            OutputStream outputStream = conn.getOutputStream();
            // 注意编码格式
            outputStream.write(outputStr.getBytes("UTF-8"));
            outputStream.close();
        }

        // 从输入流读取返回内容
        InputStream inputStream = conn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        StringBuffer buffer = new StringBuffer();
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        // 释放资源
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        inputStream = null;
        conn.disconnect();
        json = JSON.parseObject(buffer.toString());
        String errcode = json.getString("errcode");
        if (!StringUtil.isBlank(errcode) && !errcode.equals("0")) {
            logger.error(json.toString());
            throw new SysException("ERRCODE:"+ errcode);
        }
        return json;
    }

}

原标题:java web api接口调用

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。