簡體   English   中英

如何使用HttpUrlConnection在android中構建REST客戶端

[英]how to build REST client in android using HttpUrlConnection

我想構建一個消耗一些REST API的Android應用程序。

我正在使用HttpURLConnection進行基本身份驗證和GET / PUT一些數據,但我覺得我做錯了。 我有兩個類ConnectionPUTConnectionGET ,我為每個請求調用,因為每個HttpURLConnection實例用於發出單個請求。

使用HttpURLConnection在Android上構建REST客戶端的正確方法是什么?

這是在Android中使用HttpUrlConnection調用Http GET的示例代碼。

  URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("your-url-here");

        urlConnection = (HttpURLConnection) url
                .openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();


}    
    }

但我強烈建議您不要重新發明用於為Android應用程序創建REST客戶端的輪子,而是嘗試使用Retrofit和Volley等適應性強且可靠的庫來進行網絡連接。

它們非常可靠並經過測試,並刪除了您為網絡通信編寫的所有樣板代碼。

有關更多信息,我建議您學習以下有關Retrofit和Volley的文章

Android - 使用Volley進行網絡連接

Android-使用網絡改造

使用HttpURLConnection的REST客戶端

try {

        URL url = new URL("YOUR_URL");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));

        StringBuffer data= new StringBuffer(1024);
        String tmpdata="";
        while((tmpdata=reader.readLine())!=null) {              

               data.append(tmpdata).append("\n");

           }
        reader.close();

     }catch(Exception e){  
             e.printStackTrace();

        } finally {

         if (conn!= null) {
             conn.disconnect();

            } 

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM