java後臺建立url連線,獲取介面資料

塵光掠影發表於2018-01-05
版權宣告:本文為博主原創文章,如需轉載,請標明出處。 https://blog.csdn.net/alan_liuyue/article/details/78982905

簡介

  1. 在實踐中,當專案不斷進行新功能開發的時候,我們就不可能將所有的方法、功能點全部都寫在同一個專案裡面,這樣也不符合脫耦的趨勢;
  2. 那麼,在專案中,我們既要增加新的功能點,又要最大限度地降低耦合度,我們就要不斷地對介面進行深入發掘;
  3. 像阿里的分散式服務框架dubbo,也是一種基於介面開發的服務框架,它不僅能鬆耦合,而且功能點都是通過不斷增加介面來不斷增加;
  4. 本篇部落格不講述介面如何開發,而是簡單地介紹,如何通過java建立url連線,獲取介面返回來的json資料;

專案實踐

/**
 * 獲取介面資料,返回json格式字串,方法1
 * @param url 介面路徑
 * @param params 傳遞引數,自定義
 * @param key 傳遞引數標識,自定義
 * @return
 */
public String getData1(String url,String params,String key){

        String rs = null;
        CloseableHttpClient httpClient = HttpClient.createDefault();
        try{
            //拼接引數,轉義引數
            String connUrl = url+"?params="+URLEncoder.encode(params,HTTP.UTF-8)+"&key="+key;

            //建立連線
            HttpGet get = new HttpGet(connUrl);

            //獲取以及解析資料
            CloseableHttpResponse resp = httpClient.execute(get);
            rs = EntityUtils.toString(resp.getEntity(),HTTP.UTF-8);

        }catch(IOException e){
            System.out.println("出錯了")
        }
        return rs;

}

/**
 * 獲取介面資料,返回json格式字串,方法2
 * @param url 介面路徑
 * @param params 傳遞引數,自定義
 * @param key 傳遞引數標識,自定義
 * @return
 */
public String getData2(String url,String params,String key){

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            //拼接引數,轉義引數
            String connUrl = url+"?params="+URLEncoder.encode(params,HTTP.UTF-8)+"&key="+key;

            //建立連線
            URL url = new URL(connUrl); 
            conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            conn.connect();

            //獲取並解析資料
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
}

總結

  1. 上面提供了兩種方法來建立連線,獲取介面資料,可自選比較合適的方法;
  2. 返回的rs都是json格式的字串,可直接使用JSONObject object = JSONObject.fromObject(rs)來轉換成json物件,然後進行多層次的解析;
  3. 實踐是檢驗認識真理性的唯一標準,試一試就知道好不好用了;


相關文章