java web api接口调用

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

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

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

Web Services 全部基于XML。按照W3C标准来描述服务的各个方面(参数、参数传递、返回值及服务发布发现等)。要描述清楚Web Services标准的各个方面,可能需要2000页的文档。
Web Services 还有标准的身份验证方式(非公共服务时验证使用者身份)。

轻量化的Web API

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

Web API一般基于HTTP/REST来实现,什么都不需要定义,参数(输入的数据)可以是JSON, XML或者简单文本,响应(输出数据)一般是JSON或XML。它不提供服务调用标准和服务发现标准。可以按你服务的特点来写一些简单的使用说明给使用者。

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

Web Services的架构要比Web API臃肿得多,它的每个请求都需要封装成XML并在服务端解封。因此它不易开发且吃更多的资源(内存、带宽)。性能也不如Web API。

   

  /**
     * 根据指定url,编码获得字符串 官网:www.fhadmin.org
     * 
     * @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请求 官网:www.fhadmin.org
     * @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;
    }

}

猜你喜欢

转载自zhoumeng87.iteye.com/blog/2390109