网络技术

声明权限

WebView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
WebView webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true); //通过getSettings()设置浏览器属性 setJavaScriptEnabled(true)让Webview支持javaScript脚本
webView.loadUrl("https://www.baidu.com");
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url == null) return false;

try{
if(!url.startsWith("http://") && !url.startsWith("https://")){
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}catch (Exception e){//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
return true;//没有安装该app时,返回true,表示拦截自定义链接,但不跳转,避免弹出上面的错误页面
}

// TODO Auto-generated method stub
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
view.loadUrl(url);
return true;
}
});
解决ERR_UNKNOWN_URL_SCHEME这个错误

给WebView设置WebViewClient,并重写WebViewClient中的shouldOverrideUrlLoading方法.
首先我们来了解下shouldOverrideUrlLoading(WebView view, String url)方法,该方法会在加载超链接时回调过来,所以通过重写shouldOverrideUrlLoading,可以实现对网页中超链接的拦截;返回值为boolean型,是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器。默认false

Http协议访问

HttpURLConnection

1.传入URL对象通过openConnection()获取HttpURLConnection对象

               URL url = new URL("http://www.baidu.com");
               connection = (HttpURLConnection) url.openConnection();

2.设置HTTP属性 如 请求方法 get post 连接超时

               connection.setRequestMethod("GET");
               connection.setConnectTimeout(8000);
               connection.setReadTimeout(8000);

3.获取输入流并读取

                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());

4.输出流

                connection.setRequestMethod("GET");
                DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
                outputStream.writeBytes("xxxxxxx");

5.关闭连接

                    connection.disconnect();

一般在应用中的 放在中多线程实例

    public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        // 回调onFinish()方法
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        // 回调onError()方法
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    public static void sendOkHttpRequest(final String address, final okhttp3.Callback callback) {
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
   }
<!--code1-->
#### GSON
自动将JSON格式映射成对象。
1.加库
>     implementation 'com.google.code.gson:gson:2.7'
2.解析
>        Gson gson = new Gson();
>        JAVABean javabean = gson.fromJson(jsondata, Person.class);
        
当是Json数组时 借助TypeToken将期望解析成的数据类型(javabean)传入fromjson()中。
<!--code2-->