首页 > 其他 > 详细

Unit9:网络技术

时间:2020-09-21 16:31:23      阅读:33      评论:0      收藏:0      [点我收藏+]

1. 使用webView

res中:

  <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/web_view"
        />

java中:

        WebView webView = findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());  // 网页跳转在WebView中显示
        webView.loadUrl("http://www.baidu.com");

.xml中:

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        ...
        android:requestLegacyExternalStorage="true"
        android:usesCleartextTraffic="true">

2. 发送HTTP

1.httpconnection

       textView = findViewById(R.id.text_view);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        HttpURLConnection connection = null;
                        BufferedReader reader = null;

                        try {
                            URL url = new URL("http://www.baidu.com");
                            connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setConnectTimeout(8000);
                            connection.setReadTimeout(8000);
                            InputStream in = connection.getInputStream();
                            reader = new BufferedReader(new InputStreamReader(in));
                            StringBuilder response = new StringBuilder();
                            String line;
                            while ((line = reader.readLine()) != null) {
                                response.append(line);
                            }
                            showResponse(response.toString());

                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (reader != null) {
                                try {
                                    reader.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (connection != null) {
                                connection.disconnect();
                            }
                        }
                    }
                }).start();

            }
        });

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText(response);
            }
        });
    }

.xml中:

添加权限控制,如上

2.OkHttp
.gradle中:

      implementation ‘com.squareup.okhttp3:okhttp:3.10.0‘  

java中:

                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url("http://www.baidu.com")
                                .build();
                        try {
                            Response response = client.newCall(request).execute();
                            String responseData = response.body().string();
                            showResponse(responseData);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

.xml中:

引入权限控制,如上

3. xml解析

1.PULL

//    解析xml文件
    private void parseXMLWithPull(String xmlData) {
        XmlPullParserFactory factory = null;
        try {
            factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
//                    开始解析某个节点
                    case XmlPullParser.START_TAG: {
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    }
//                    完成解析某个节点
                    case XmlPullParser.END_TAG: {
                        if ("app".equals(nodeName)) {
                            System.out.println("id is " + id);
                            System.out.println("name is " + name);
                            System.out.println("version is " + version);
                        }
                        break;
                    }
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

2.SAX
.java中:

继承DefaultHandler类:

public class ContentHandler extends DefaultHandler {
    private String nodeName;

    private StringBuilder id;

    private StringBuilder name;

    private StringBuilder version;
    /**
     * 开始解析的时候调用
     */
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
    }

    /**
     * 开始解析某个节点的时候调用
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
//        记录当前节点名称
        nodeName = localName;
    }

    /**
     * 获取节点内容的时候调用
     */
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
//        根据当前节点名称判断将内容添加到哪个StringBuilder对象中
        if ("id".equals(nodeName)) {
            id.append(ch,start,length);
        } else if ("name".equals(nodeName)) {
            name.append(ch,start,length);
        } else if ("version".equals(nodeName)) {
            version.append(ch,start,length);
        }
    }

    /**
     * 完成某个节点的时候调用
     */
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if ("app".equals(localName)) {
            System.out.println("id is " + id.toString().trim());
            System.out.println("name is " + name.toString().trim());
            System.out.println("version is " + version.toString().trim());
//            最后要将StringBuilder清空掉,不然影响下一次内容读取
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    }

    /**
     * 完成整个xml解析的时候调用
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }
}

java.activity中:

    private void parseXMLWithSAX(String xmlData) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
//            将ContentHandler的实例设置到XMLReader中
            xmlReader.setContentHandler(handler);
//            开始执行解析
            xmlReader.parse(new InputSource(new StringReader(xmlData)));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

4. JSON解析

1.JSONObject

    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                System.out.println("id is " + id);
                System.out.println("name is " + name);
                System.out.println("version is " + version);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.GSON
.gradle中:

      implementation ‘com.google.code.gson:gson:2.8.4‘

java中:

新建App类,作为映射对象

java.Activity中:

    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {
        }.getType());
        for (App app:appList
             ) {
            System.out.println("id is " + app.getId());
            System.out.println("name is " +app.getName());
            System.out.println("version is " +app.getVersion());
        }
    }

Unit9:网络技术

原文:https://www.cnblogs.com/ssy197/p/13705284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!