有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用HttpUrlConnection在安卓中构建REST客户端

我想构建一个使用REST API的安卓应用程序

我使用HttpURLConnection进行基本的身份验证并获取/放置一些数据,但我觉得我做得不对。 我为每个请求调用了两个类ConnectionPUTConnectionGET,因为每个HttpURLConnection实例都用于发出单个请求

使用HttpURLConnection在Android上构建REST客户端的正确方法是什么


共 (2) 个答案

  1. # 1 楼答案

    使用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();
    
                } 
    
            }
    
  2. # 2 楼答案

    这是在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客户端,而应该尝试使用经过良好调整且可靠的库,如Refundation和Volley,用于联网

    它们是高度可靠且经过测试的,并且删除了所有必须为网络通信编写的样板代码

    要了解更多信息,我建议您学习以下关于改装和截击的文章

    Android - Using Volley for Networking

    Android -Using Retrofit for Networking