Android开发Android技术知识

Android之网络编程

2019-09-29  本文已影响0人  拨云见日aaa

一、简介

二、WebView

(1)用法介绍

创建WebView实例,调用WebView.getSettings设置一些设置,例如设置能否使用Javascript(setJavaScriptEnable)等,调用setWebViewClient设置WebViewClient(防止网页跳转时调用别的浏览器,重写里面的shouldOverrideUrlLoading方法),调用loadUrl设置打开的url

(2)代码示例
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv=findViewById(R.id.wv);
        wv.loadUrl("https://www.baidu.com");//设置url
        wv.getSettings().setJavaScriptEnabled(true);//设置能否使用javascript
        wv.setWebViewClient(new WebViewClient(){//设置WebViewClient

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {//重写shouldOverrideUrlloading方法
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        });
    }
}
(3)效果展示
WebView打开百度页面

三、HttpURLConnection

(1)用法介绍

首先创建URL类,然后调用URL.openConnection获取HttpURLConnection实例,再通过设置请求方法(setRequestMethod),设置连接时间(setConnectTimeout)获取结果码(getResponseCode),获取响应的输入流

(2)代码示例
public class MainActivity extends AppCompatActivity {
TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=findViewById(R.id.tv);
        new Thread(){   //注意联网请求不要在ui线程里做,要新起一个线程
            URL url;
            StringBuffer str;
            public void run(){
                try {
                    url=new URL("http://10.4.1.39:8080/news.xml");
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");//设置请求方式
                    connection.setConnectTimeout(5000);//设置连接超时时间
                    int code=connection.getResponseCode();//获取响应码
                    if(code==200){
                        str=new StringBuffer();
                        String buffer=new String();
                        InputStream is=connection.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        while((buffer=br.readLine())!=null){
                            str.append(buffer);
                        }
                    }
                    runOnUiThread(new Thread(){
                        public void run(){
                            tv.setText(str);
                        }
                    });
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
(3)效果展示
读取的xml
(4)注意

四、OkHttp

(1)用法介绍

首先创建一个OkHttpClient对象,然后通过调用Request.bulder对象的bulid建立一个Request对象(在build之前可以做很多设置比如url),然后建立一个Call对象调用Execute方法返回的是Response对象
用法也可以参考:GitHub的示例

(2)代码示例

get请求

public class MainActivity extends AppCompatActivity {
TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=findViewById(R.id.tv);
        new Thread(){
            OkHttpClient client =new OkHttpClient();
            Response response;
            public void run(){
                Request request=new Request.Builder().url("http://10.4.1.39:8080/news.xml").build();
                try {
                    response=client.newCall(request).execute();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                tv.setText(response.body().string());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

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

post请求

public class MainActivity extends AppCompatActivity {
TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=findViewById(R.id.tv);
        new Thread(){
            OkHttpClient client =new OkHttpClient();
            RequestBody body=new FormBody.Builder().add("","").build();//设置请求体
            Response response;
            public void run(){
                Request request=new Request.Builder().url("http://10.4.1.39:8080/news.xml").post(body).build();
                try {
                    response=client.newCall(request).execute();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                tv.setText(response.body().string());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
(3)运行结果
okhttp访问xml
上一篇下一篇

猜你喜欢

热点阅读