安卓Java使用GET、POST请求获取数据并显示

1.获取数据

服务器返回的数据格式为JSON,下面获取到的数据:

"message": {
        "creator0": "用户",
        "creator1": "超级用户",
        "creator2": "用户3",
        "creator3": "用户2",
        "creator4": "用户1",
        "message0": "直播",
        "message1": "hello",
        "message2": "你好你好",
        "message3": "你好",
        "message4": "大家好"
    },

1.1 GET请求

编写获取数据函数:
需要定义全局变量:String msg=""

private void getMessage(){
        System.out.println(" begin to get message!");
        try {
            URL url = new URL("http://114.115.206.93:5000/get_gps_st_data");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                // 解析JSON数据
                JSONObject jsonObject = new JSONObject(response.toString());
                // 获取需要的字段
                JSONObject json= (JSONObject) jsonObject.get("message");
                for(int i=0;i<5;i++){
                    msg+=json.get("creator"+i)+":" +json.get("message"+i) +"\n";
                }
                System.out.println("msg:"+msg);
                Message message = new Message();
                mHandler.sendMessage(message);
            } else {
                System.out.println("GET request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.2 POST请求

private void getMessagePost(){
        System.out.println(" begin to get sankey data!");
        try {
            URL url = new URL("http://114.115.206.93:5000/get_sankey_data");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setUseCaches(false); //关闭缓存
            //post的方式提交实际上是留的方式提交给服务器
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //json待传输的数据
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("min",1);
            jsonObject.put("max",10);
            String data=jsonObject.toString();
            //至少要设置的两个请求头
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");  //application/json传输json数据格式
            connection.setRequestProperty("Content-Length", data.length()+"");
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(data.getBytes());
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println(response.toString());
            } else {
                System.out.println("POST request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.3 启用子线程

new Thread(){
              @Override
              public void run() {
                  getMessage();
               }
             }.start();

2.TextView显示数据

需要启用新UI线程,获取数据结束后将数据更新在textview:

Handler mHandler = new Handler(){
        public void handleMessage(Message message) {
            //要做的事情
            messageView.setText(msg);
            super.handleMessage(message);
        }
    };

3.结果

4.仓库地址

https://gitee.com/junleea/video_play.git

暂无评论

发送评论 编辑评论


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