繁体   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