java web api接口調用

Web Services 被W3C進行了標準化定義。

Web Services 發佈到網上,能夠公佈到某個全局註冊表,自動提供服務URL,服務描述、接口調用要求、參數說明以及返回值說明。好比中國氣象局能夠發佈天氣預報服務。全部其它網站或手機App若是須要集整天氣預報功能,均可以訪問該Web Service獲取數據。java

Web Services 主要設計目標是提供公共服務。

Web Services 所有基於XML。按照W3C標準來描述服務的各個方面(參數、參數傳遞、返回值及服務發佈發現等)。要描述清楚Web Services標準的各個方面,可能須要2000頁的文檔。
Web Services 還有標準的身份驗證方式(非公共服務時驗證使用者身份)。json

輕量化的Web API

公司內部使用的私有服務,咱們知道它的接口Url,所以不須要自動發現它。咱們有它的服務接口文檔,所以也不須要自動描述和自動調用。
即便Web Services的特性(自動發現、自動學會調用方式)很美好,但私有服務每每不須要這些。架構

Web API通常基於HTTP/REST來實現,什麼都不須要定義,參數(輸入的數據)能夠是JSON, XML或者簡單文本,響應(輸出數據)通常是JSON或XML。它不提供服務調用標準和服務發現標準。能夠按你服務的特色來寫一些簡單的使用說明給使用者。app

獲取遠程數據的方式正在從Web Services向Web API轉變。

Web Services的架構要比Web API臃腫得多,它的每一個請求都須要封裝成XML並在服務端解封。所以它不易開發且吃更多的資源(內存、帶寬)。性能也不如Web API。dom

  

 

  /**
     * 根據指定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();
    }ide

    /**
     * 經過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();
    }post

    /**
     * 發送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;
    }

}性能

相關文章
相關標籤/搜索