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的特性(自动发现、自动学会调用方式)很美好,但私有服务往往不需要这些。

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

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

Web Services的架构要比Web API臃肿得多,它的每个请求都需要封装成XML并在服务端解封。因此它不易开发且吃更多的资源(内存、带宽)。性能也不如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接口调用的更多相关文章

  1. WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递

    回到目录 上一讲中介绍了使用HttpClient如何去调用一个标准的Web Api接口,并且我们知道了Post,Put方法只能有一个FromBody参数,再有多个参数时,上讲提到,需要将它封装成一个对 ...

  2. Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口

    1.WebApi系列~通过HttpClient来调用Web Api接口 http://www.cnblogs.com/lori/p/4045413.html HttpClient使用详解(java版本 ...

  3. ASP.NET Web API 接口执行时间监控

    软件产品常常会出现这样的情况:产品性能因某些无法预料的瓶颈而受到干扰,导致程序的处理效率降低,性能得不到充分的发挥.如何快速有效地找到软件产品的性能瓶颈,则是我们感兴趣的内容之一. 在本文中,我将解释 ...

  4. Web API接口之FileReader

    Web API接口之FileReader *:first-child { margin-top: 0 !important; } body>*:last-child { margin-botto ...

  5. Winform混合式开发框架访问Web API接口的处理

    在我的混合式开发框架里面,集成了WebAPI的访问,这种访问方式不仅可以实现简便的数据交换,而且可以在多种平台上进行接入,如Winform程序.Web网站.移动端APP等多种接入方式,Web API的 ...

  6. Web API接口设计经验总结

    在Web API接口的开发过程中,我们可能会碰到各种各样的问题,我在前面两篇随笔<Web API应用架构在Winform混合框架中的应用(1)>.<Web API应用架构在Winfo ...

  7. 如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问。

    由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题. 刚开始没做任何处理,用jsonp的方式调用 web api 接口, ...

  8. Web API接口 安全验证

    在上篇随笔<Web API应用架构设计分析(1)>,我对Web API的各种应用架构进行了概括性的分析和设计,Web API 是一种应用接口框架,它能够构建HTTP服务以支撑更广泛的客户端 ...

  9. Asp.Net Web Api 接口,拥抱支持跨域访问。

    如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问. 由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题 ...

随机推荐

  1. ASP.NET-GridView之表头设计

    我们 见过许多网页呈现表格的 时候,表头的形式多种多样.下面来看看,怎么制定多样的表头吧. 效果显示: 需要在后台写一个方法,网页一加载在前端写个事件调用这个方法. DEMO 前端 <span ...

  2. Ready api groovy script 参数化

    def token_type =context.expand ('${#Project#token_type}') def access_token = context.expand('${#Proj ...

  3. 使用Spring IOC容器引用外部属性文件

    一.引用外部属性文件 1.编写属性文件,以键值对形式存储,并放置在类路径(src)下 jdbc.jdbcUrl=jdbc:mysql://localhost:3306/BOOKSTORE?rewrit ...

  4. 树形DP【洛谷P3047】 [USACO12FEB]附近的牛Nearby Cows

    P3047 [USACO12FEB]附近的牛Nearby Cows 农民约翰已经注意到他的奶牛经常在附近的田野之间移动.考虑到这一点,他想在每一块土地上种上足够的草,不仅是为了最初在这片土地上的奶牛, ...

  5. #!/usr/bin/env python 是什么

    #!/usr/bin/env python 这一行注释经常出现在Python脚本的第一行.这一行到底用来干嘛的呢?原因很简单,任何Python脚本执行都需要靠Python解释器.这一行注释正是告诉计算 ...

  6. 【笔记】MySQL的基础学习(二)

    [笔记]MySQL的基础学习(二) MySQL 老男孩  一 视图 视图其实就是给表起个别名 1.创建视图 格式:CREATE VIEW 视图名称 AS SQL语句 CREATE VIEW v1 AS ...

  7. HDU - 1042-N!(Java)

    Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N! Input One N in one line, process to ...

  8. Codeforces Round #335 (Div. 2) C

                                                                   C. Sorting Railway Cars time limit pe ...

  9. Java类名 方法名 常量 变量的命名习惯

    1.包 用于将完成不同功能的类分门别类,放在不同的目录(包)下,包的命名规则:将公司域名反转作为包名,对于包名,每个字母都需要小写. 如果定义类的时候没有使用package(包),那么java就认为我 ...

  10. Java升级替换java version "1.5.0"

    首先进行java安装 http://www.cnblogs.com/someone9/p/8670585.html 2. 然后查看版本信息,仍然是1.5.0 [root@OKC java]# java ...