网络技术
网络技术
声明权限
WebView
1 | WebView webView = (WebView) findViewById(R.id.web_view); |
解决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-->
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Raykie’s blog!
评论