主要分为三点补充

1.get和post方式请求访问网络
记得一定要处理异常
package com.example.four_content;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class Get_Post_Activity {
    public static String get(String path) {
        String result = null;
        try {
            URL url = new URL(path);    //创建url对象
            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("GET");   //设置请求方式
            coon.setConnectTimeout(5000);   //设置超时时间
            int responseCode = coon.getResponseCode();  //获取状态码
            if (responseCode == 200) {
                InputStream is = coon.getInputStream(); //获取服务器返回的输入流
                //使用InputStreamReader和BufferedReader来读取输入流的内容 这里还指定了字符编码为UTF-8
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    //使用StringBuilder来拼接从输入流中读取的每一行内容。每读取一行,都会在其后添加系统行分隔符
                    stringBuilder.append(line).append(System.lineSeparator());
                }
                result = stringBuilder.toString();
            }

        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }


    public static String post(String path, Map<String, Object> map) {
        String result = null;
        try {
            URL url = new URL(path);
            HttpURLConnection coon = (HttpURLConnection) url.openConnection();
            coon.setRequestMethod("POST");
            coon.setConnectTimeout(5000);


            String data = "";
            //设置Content-Type 用于指定提交的实体数据的内容类型
            coon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置Content-Length提交数据的长度
            coon.setRequestProperty("Content-Length", data.length() + "");
            coon.setDoOutput(true);     //设置允许向外写数据
            //获取输出流 向服务器写数据
            OutputStream outputStream = coon.getOutputStream();
            outputStream.write(data.getBytes());

            int responseCode = coon.getResponseCode();
            if (responseCode == 200) {
                InputStream is = coon.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append(System.lineSeparator());
                }
                result = stringBuilder.toString();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
  new Thread() {
            @Override
            public void run() {
                    //                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                    //                String s = Get_Post_Activity.post("http://本机ip地址:8080/Chapter09/goods/goods_list_data.json",objectObjectHashMap);
                    String s = Get_Post_Activity.get("http://本机ip地址:8080/Chapter09/goods/goods_list_data.json");
              Log.i("高远", "RUN:"+ s);
 }
}
2.解析json数据

image

也别忘记处理异常
                    // 1.JSONArray类解析
                    JSONArray jsonArray = new JSONArray(s);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        //JSONObject类解析对象结构的json数据
                        JSONObject jsonObj = jsonArray.getJSONObject(i);
                        String id = jsonObj.optString("id");
                        String count = jsonObj.optString("count");
                        String goodsName = jsonObj.optString("goodsName");
                        String goodsPic = jsonObj.optString("goodsPic");
                        Log.i("高远", "run: " + id + count + goodsName + goodsPic);
                    }

                    // 2.使用Gson库解析
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<Goods>>() {
                    }.getType();
                    List<Goods> goods = gson.fromJson(s, type);
                    for (Goods good : goods) {
                        int id = good.getId();
                        String goodsName = good.getGoodsName();
                        String count = good.getCount();
                        String goodsPic = good.getGoodsPic();
                        Log.i("低近", "run: " + id + count + goodsName + goodsPic);
                    }
3.对handler的再理解
之前那个项目里的MHandle为主线程 所有操作在这个内部完成 子线程向主线程发送消息
    class MHandle extends Handler {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == MSG_GOODS_OK) {
                if (msg.obj != null) {
                    String result = (String) msg.obj;
                    List<Goods> goodsList = getGoodsList(result);
                    pddAdapter.setData(goodsList);
                }
            }
        }
    }
posted on 2024-06-01 10:16  蒸饺  阅读(15)  评论(0)    收藏  举报