Android笔记9---网络技术

[1]WebView的用法

1.主程序中

public class MainActivity extends AppCompatActivity {

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

        WebView webView =findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true); //设置浏览器属性支持js脚本
        webView.setWebViewClient(new WebViewClient()); //使跳转网页仍然在webview中
        webView.loadUrl("https://www.baidu.com");
    }
}

2.权限

<uses-permission android:name="android.permission.INTERNET"/>

[2]OkHttpClient完美取代HttpUrlConnection

1.build.gradle中设置:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'    //3.4.1版本可用
}

2.主程序中的示例代码

 public void send(View v){
        //Toast.makeText(MainActivity.this,"请开始",Toast.LENGTH_SHORT).show();
        if(v.getId()==R.id.send){
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {

                String path = editText.getText().toString().trim();
                try {
                    OkHttpClient client = new OkHttpClient();     //创建OkHttpClient实例
                    Request request = new Request.Builder()      //要发起http请求,就需要创建request对象
                        .url(path).build();                      //通过url()设置目标网址
                 
                   Response response= client.newCall(request).execute();
                    //调用newCall方法创建Call对象,调用excute方法来发送请求并获取服务器返回的数据
                 
                   final String responseData = response.body().string(); //返回具体的内容
                   
                    runOnUiThread(new Runnable() {           //将线程切换成主线程,更新UI元素
                        @Override
                        public void run() {
                            show.setText(responseData);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

OkHttpClient发送post请求

1.先构建Request Body对象

RequestBody requestBody = new FormBody.Builder()
	.add("username","admin")
	.add("password","123456")
	.build();

2.在Request.Builder中调用post方法,并把RequestBody传入

    Request request =new Request.Builder()
    	.ur("http://www.baidu.com")
    	.post(requestBody)
    	.build();

[3]Pull解析XML

关键代码:

 public void send(View v){
        //Toast.makeText(MainActivity.this,"请开始",Toast.LENGTH_SHORT).show();
        if(v.getId()==R.id.send){
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                //http://172.30.27.15/get_data.xml
                String path = editText.getText().toString().trim();
                try {
                    OkHttpClient client = new OkHttpClient(); //创建OkHttpClient实例
                    Request request = new Request.Builder()    //要发起http请求,就需要创建request对象
                        .url(path).build();//通过url()设置目标网址
                   Response response= client.newCall(request).execute();
                    //调用newCall方法创建Call对象,调用excute方法来发送请求并获取服务器返回的数据
                   final String responseData = response.body().string(); //返回具体的内容
                    ParseXmlWithPull(responseData);

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

    private void ParseXmlWithPull(String xmlData) {

        try {
            XmlPullParserFactory 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)){
                            Log.d("MainActivity","ID is"+id);
                            Log.d("MainActivity","name is"+name);
                            Log.d("MainActivity","version is"+version);
                        }
                        break;

                    }
                    default:break;

                }
                eventType=xmlPullParser.next();
            }


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

    }

}

[3]Sax解析XML

1.新建一个类继承DefaultHandler

public class ContentHandler extends DefaultHandler {
    private String nodeName;
    private StringBuilder id;
    private  StringBuilder name;
    private  StringBuilder version;

    //需要重写父类的5个方法
    @Override
    public void startDocument() throws SAXException {
        id= new StringBuilder();
        name= new StringBuilder();
        version= new StringBuilder();
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //记录当前节点名
        nodeName=localName;
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if("app".equals(localName)){
            Log.d("ContentHandler","id is"+id.toString().trim());
            Log.d("ContentHandler","name is"+name.toString().trim());
            Log.d("ContentHandler","version is"+version.toString().trim());
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //根据当前节点名判断将内容添加到哪一个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);
        }
    }
}

2.主程序中

ublic void send(View v){
        //Toast.makeText(MainActivity.this,"请开始",Toast.LENGTH_SHORT).show();
        if(v.getId()==R.id.send){
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                //http://172.30.27.15/get_data.xml
                String path = editText.getText().toString().trim();
                try {
                    OkHttpClient client = new OkHttpClient(); //创建OkHttpClient实例
                    Request request = new Request.Builder()    //要发起http请求,就需要创建request对象
                        .url(path).build();//通过url()设置目标网址
                   Response response= client.newCall(request).execute();
                    //调用newCall方法创建Call对象,调用excute方法来发送请求并获取服务器返回的数据
                   final String responseData = response.body().string(); //返回具体的内容
                    ParseXmlWithSAX(responseData);

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

    private void ParseXmlWithSAX(String xmlData) {
        try {
            SAXParserFactory factory =SAXParserFactory.newInstance();
            //创建SAX解析实例
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            //获取到XMLReader对象
            ContentHandler handler = new ContentHandler();   //创建解析对象
            xmlReader.setContentHandler(handler);  // 将ContentHandler实例设置到xmlreader中
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

[4]JSONObject解析json

  public void send(View v){
        //Toast.makeText(MainActivity.this,"请开始",Toast.LENGTH_SHORT).show();
        if(v.getId()==R.id.send){
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                //http://172.30.27.15/get_data.json
                String path = editText.getText().toString().trim();
                try {
                    OkHttpClient client = new OkHttpClient(); //创建OkHttpClient实例
                    Request request = new Request.Builder()    //要发起http请求,就需要创建request对象
                        .url(path).build();//通过url()设置目标网址
                   Response response= client.newCall(request).execute();
                    //调用newCall方法创建Call对象,调用excute方法来发送请求并获取服务器返回的数据
                   final String responseData = response.body().string(); //返回具体的内容
                    ParseJsonWithJSONObject(responseData);

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

    private void ParseJsonWithJSONObject(String jsonData) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData); //创建json数组对象
            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");
                Log.d("MainActivity","ID is"+id);
                Log.d("MainActivity","name is"+name);
                Log.d("MainActivity","version is"+version);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

[5]Gson解析json

1.build.gradle中加入gson
implementation ‘com.google.code.gson:gson:2.8.2’

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'
    implementation 'com.google.code.gson:gson:2.8.2'
}

2.新建一个App类

public class App {
    private String id;
    private String name;
    private String version;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

3.主程序中

  private void ParseJsonWithGson(String jsonData) {
        Gson gson = new Gson(); //创建Gson对象
        List<App> appList =gson.fromJson(jsonData,new TypeToken<List<App>>()
        {}.getType());
        for (App app:appList){
            Log.d("MainActivity","id is"+app.getId());
            Log.d("MainActivity","name is"+app.getName());
            Log.d("MainActivity","version is"+app.getVersion());

        }

    }

[6]通用网络操作

 public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private Button send;
    private TextView show;
    private String responseData;

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

        editText = findViewById(R.id.edit_text);
        send = findViewById(R.id.send);
        show = findViewById(R.id.show);
    }
    public void send(View v){
        //http://172.30.27.15/get_data.json
  String path = editText.getText().toString().trim();
        if(v.getId()==R.id.send){
            HttpUtil.sendOkHttpRequest(path, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    responseData = response.body().string();
                    ParseJsonWithGson(responseData);
                }
            });
        }
    }
     private void ParseJsonWithGson(String jsonData) {
        Gson gson = new Gson();       //创建Gson对象
        List<App> appList =gson.fromJson(jsonData,new TypeToken<List<App>>()
        {}.getType());
        for (App app:appList){
            Log.d("MainActivity","id is"+app.getId());
            Log.d("MainActivity","name is"+app.getName());
            Log.d("MainActivity","version is"+app.getVersion());
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值