android network develop(1)----doing network background
Develop network with HttpURLConnection & HttpClient.
HttpURLConnection is lightweight with HttpClient.
So normally, you just need HttpURLConnection.
NetWork is a timer wast task, so it is better doing this at asynctask.
package com.joyfulmath.androidstudy.connect; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL; import com.joyfulmath.androidstudy.TraceLog; import android.os.AsyncTask; public class NetWorkHandle { private onDownLoadResult mResultListener = null; public class DownloadWebpageTask extends AsyncTask<String, Void, String>{ public DownloadWebpageTask(onDownLoadResult resultListener )
{
mResultListener = resultListener;
} @Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
} // onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
mResultListener.onResult(result);
}
} private String downloadUrl(String myurl) throws IOException{ InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500; try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
TraceLog.d("The response is: " + response);
is = conn.getInputStream(); // Convert the InputStream into a string
// String contentAsString = readIt(is, len);
StringBuilder builder = inputStreamToStringBuilder(is);
conn.disconnect();
return builder.toString(); // Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
} // 将InputStream 格式转化为StringBuilder 格式
private StringBuilder inputStreamToStringBuilder(InputStream is) throws IOException {
// 定义空字符串
String line = "";
// 定义StringBuilder 的实例total
StringBuilder total = new StringBuilder();
// 定义BufferedReader,载入InputStreamReader
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// readLine 是一个阻塞的方法,当没有断开连接的时候就会一直等待,直到有数据返回
// 返回null 表示读到数据流最末尾
while ((line = rd.readLine()) != null) {
total.append(line);
}
// 以StringBuilder 形式返回数据内容
return total;
} // 将InputStream 格式数据流转换为String 类型
private String inputStreamToString(InputStream is) throws IOException {
// 定义空字符串
String s = "";
String line = "";
// 定义BufferedReader,载入InputStreamReader
BufferedReader rd = new BufferedReader(new InputStreamReader(is,"UTF-8"));
// 读取到字符串中
while ((line = rd.readLine()) != null) {
s += line;
}
// 以字符串方式返回信息
return s;
} // Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
} public interface onDownLoadResult{
void onResult(String result);
}
}
this is a async handle to download content with url.
package com.joyfulmath.androidstudy.connect; import com.joyfulmath.androidstudy.R;
import com.joyfulmath.androidstudy.TraceLog;
import com.joyfulmath.androidstudy.connect.NetWorkHandle.onDownLoadResult; import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.EditText; public class NetWorkActivty extends Activity implements onDownLoadResult{ EditText mEdit = null;
WebView mContent = null;
WebView mWebView = null;
NetWorkHandle netHandle = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.network_layout);
mEdit = (EditText) findViewById(R.id.url_edit);
mEdit.setText("http://www.163.com");
mContent = (WebView) findViewById(R.id.content_view);
mWebView = (WebView) findViewById(R.id.webview_id);
netHandle = new NetWorkHandle();
mContent.getSettings().setDefaultTextEncodingName("UTF-8");
} @Override
protected void onResume() {
super.onResume(); } @Override
protected void onPause() {
super.onPause();
} @Override
protected void onDestroy() {
super.onDestroy();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem connect = menu.add(0, 0, 0, "connect");
connect.setIcon(R.drawable.connect_menu);
return super.onCreateOptionsMenu(menu);
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == 0)
{
stratConnect();
return true;
} return super.onOptionsItemSelected(item);
} private void stratConnect() {
String stringurl = mEdit.getText().toString();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getActiveNetworkInfo();
if(info!=null && info.isConnected())
{
netHandle.new DownloadWebpageTask(this).execute(stringurl);
}
else
{
String mimeType = "text/html";
mContent.loadData("No network connection available", mimeType, null);
} mWebView.loadUrl(stringurl);
} @Override
public void onResult(String result) {
TraceLog.d("result length"+result.length());
TraceLog.i(result);
String mimeType = "text/html";
mContent.loadData(result, "text/html; charset=UTF-8", null);
} }
As you see, there are two webview.
One is loading with:
mContent.loadData(result, "text/html; charset=UTF-8", null);
and another one is :
mWebView.loadUrl(stringurl);
as result is loadUrl is very fast, but you can not filter the result.
and for more case, we using network to connect with server.
These case may need to using network:
1.downloading file or img.
2.post some content to server.
3.update some info when server update.
PS:result may be messy code, should using following code.
mContent.loadData(result, "text/html; charset=UTF-8", null);
android network develop(1)----doing network background的更多相关文章
- Android 性能优化(5)网络优化 (1) Collecting Network Traffic Data 用Network Traffic tool :收集传输数据
Collecting Network Traffic Data 1.This lesson teaches you to Tag Network Requests 标记网络类型 Configure a ...
- POJ 1459 Power Network / HIT 1228 Power Network / UVAlive 2760 Power Network / ZOJ 1734 Power Network / FZU 1161 (网络流,最大流)
POJ 1459 Power Network / HIT 1228 Power Network / UVAlive 2760 Power Network / ZOJ 1734 Power Networ ...
- P2746 [USACO5.3]校园网Network of Schools// POJ1236: Network of Schools
P2746 [USACO5.3]校园网Network of Schools// POJ1236: Network of Schools 题目描述 一些学校连入一个电脑网络.那些学校已订立了协议:每个学 ...
- flutter doctor出现问题 [!] Android toolchain - develop for Android devices (Android SDK version 28.0.3) X Android license status unknown. Try re-installing or updating your Android SDK Manager. 的解决方案
首先,问题描述: flutter doctor Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Cha ...
- android network develop(3)----Xml Parser
Normally, there are three type parser in android. Xmlpullparser, DOM & SAX. Google recomand Xmlp ...
- android network develop(2)----network status check
Check & Get network status Normally, there will be two type with phone network: wifi & mobil ...
- Android中通过GPS或NetWork获取当前位置的经纬度
今天在Android项目中要实现一个通过GPS或NetWork来获取当前移动终端设备的经纬度功能.要实现该功能要用到Android Framework 中的 LocationManager 类.下面我 ...
- [Android]Volley源代码分析(叁)Network
假设各位看官细致看过我之前的文章,实际上Network这块的仅仅是点小功能的补充.我们来看下NetworkDispatcher的核心处理逻辑: <span style="font-si ...
- Android 使用 NYTimes Stores 缓存 network request
NYTimes Stores 是一个缓存库,在 2017年的 AndroidMakers 大会上被介绍过. https://github.com/NYTimes/Store 实现一个 Disk Cac ...
随机推荐
- 彻底搞定 C/C++ 指针
1.语言中变量的实质 要理解C指针,我认为一定要理解C中“变量”的存储实质, 所以我就从“变量”这个东西开始讲起吧! 先来理解理解内存空间吧!请看下图: 内存地址→ 6 7 8 9 10 11 12 ...
- Sphinx全文索引 第一节
1 使用场景:用来解决站内搜索的一些应用场景. 网站中的搜索(站内搜索) 系统后台中的搜索 第一种方式:PHP——>MySQL 第二种方式:MySQL<——>Sphinx:PHP—— ...
- SharePoint 2013中的爬网最佳做法
了解在 SharePoint Server 2013 中爬网的最佳做法 搜索系统对内容进行爬网,以构建一个用户可以对其运行搜索查询的搜索索引.本文包含有关如何最有效地管理爬网的建议. 本文内容: 使用 ...
- Mysql学习笔记(八)索引
PS:把昨天的学习内容补上...发一下昨天学的东西....五月三日...继续学习数据库... 学习内容: 索引.... 索引的优点: 1.通过创建唯一索引,可以保证数据库每行数据的唯一性... 2.使 ...
- Django--models表操作
需求 models对表的增删改查 知识点 1.基础操作 1.1 增 方法一 1 models.Tb1.objects.create(c1='xx', c2='oo') #增加一条数据 1 2 di ...
- Android的init过程(二):初始化语言(init.rc)解析
Android的init过程(一) 本文使用的软件版本 Android:4.2.2 Linux内核:3.1.10 在上一篇文章中介绍了init的初始化第一阶段,也就是处理各种属性.在本文将会详细分析i ...
- 一个关于explain出来为all的说明及优化
explain sql语句一个语句,得到如下结果,为什么已经创建了t_bill_invests.bid_id的索引,但却没有显示using index,而是显示all扫描方式呢,原来这还与select ...
- CSS3的变形transform、过渡transition、动画animation学习
学习CSS3动画animation得先了解一些关于变形transform.过渡transition的知识 这些新属性大多在新版浏览器得到了支持,有些需要添加浏览器前缀(-webkit-.-moz-.- ...
- Java开发中的23种设计模式(转)
设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...
- 【C#】第1章 VS2015中C#6的新特性
分类:C#.VS2015 创建日期:2016-06-12 一.简介 VS2015内置的C#版本为6.0,该版本提供了一些新的语法糖,这里仅列出个人感觉比较有用的几个新功能. 二.几个很有用的新特性 注 ...