Android开发之HttpURLConnection:与服务器的数据交换

        一个Android程序,大多数情况下都会涉及到与服务器的数据交换,而按谷哥官方的说法,推荐使用HttpURLConnection。

示例代码:

                HttpURLConnection connection = null;
                String str = null;
                try {
                    //TODO replace the value of url
                    URL url = new URL(url);
                    connection = (HttpURLConnection) url.openConnection();
                    InputStream in = new BufferedInputStream(connection.getInputStream());
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    str = "";
                    String len;
                    while ((len = br.readLine()) != null) {
                        //while the data stream is not ended
                        str = str + len;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null)
                        connection.disconnect();
                }
                //the value of str is what you need
                Log.d(“data”,str);

其中,url有你想要请求的网址,可以是api地址什么的
str即为最终获得的数据。
注意:该段程序并不能直接出现在UI主纯程中,这是Android API23之后的规定,耗时操作不能出现的UI主线程中。故需将它放在其它线程中,如AsyncTask中。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇