第九章 看看精彩的世界-使用网络技术

9.1 WebView的用法
    在res文件夹下新建xml文件夹,再在下面创建一个network_security_config.xml文件,内容如下
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>

    再在MainFest.xml 的 application 下 添加
    android:networkSecurityConfig="@xml/network_security_config"

    再添加网络权限
    <uses-permission android:name="android.permission.INTERNET" />
    在Layout中添加WebView,再在onCreate中实现赋值操作即可。再添加如下代码

            webView = (WebView) findViewById(R.id.web_view);

            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebViewClient(new WebViewClient());
            webView.loadUrl("http://www.baidu.com");


9.2 使用Http协议访问网络

    9.2.1 使用HttpURLConnection

private Button button_1;
    private TextView textView_1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button_1 = (Button) findViewById(R.id.send_request);
        textView_1 = (TextView) findViewById(R.id.response_text);

        button_1.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send_request:
                sendRequestWithHttpURLConnection();

                break;
            default:
                break;
        }
    }

    private void sendRequestWithHttpURLConnection(){
        new Thread(new Runnable() {
            @Override
            public void run() {

                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try{

                    URL url = new URL("https://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 (Exception 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_1.setText(response);
            }
        });
    }
        

    9.2.2 使用OkHttp
        第一步,添加OkHttp,Okio库,
        第二步,响应方法在线程里添加如下代码即可

        OkHttpClient client = new OkHttpClient();
        FormBody.Buider formbuilder = new FormBody.Builder;

        formbuilder.add("me_account", me_account);
        formbuilder.add("friend_account", friend_account);
        formbuilder.add("friend_massage", content);

    
        final Request request = new Request.Builder()
            .url(url)
            .post(formbuilder.build())
            .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                Toast.makeText(ChatWhitFriendActivity.this, "服务器错误,发送数据失败", Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        runOnUiThread(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                Toast.makeText(ChatWhitFriendActivity.this, "发送数据成功", Toast.LENGTH_LONG).show();
                            }
                        });
                        String res = response.body().string();
                        Log.d(TGA + "recv", res);
                    }
                });

9.3 解析XML格式数据
    优势:格式统一,符合标准;
    缺点:XML文件庞大,文件格式复杂,传输占带宽,解析XML花费较多的资源和时间;
    9.3.1 pull解析方式

    9.3.2 sax解析方式

9.4 解析JSON格式数据
    优势:体积更小,传输省流量
    缺点:语义性差

    9.4.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");
                Log.d("MainActivity", "id is " + id);
            }

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


    9.4.2 使用GSON

    第一步,添加GSON依赖的库
        compile 'com.google.code.gson:gson:2.7'
    第二步,新建一个关于值的app基类,
    第三步,
private void parseJSONWithGSON(String jsonData){

        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<list<App>>){}.getType());
        for(App app :appList ){
            Log.d("MainActivity", "id is" + app.getId());
        }

    }

    
    
    


            

发布了112 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/julicliy/article/details/104344048