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 ...
随机推荐
- [OpenCV] Image Processing - Fuzzy Set
使用模糊技术进行 (灰度变换Grayscale Transform) 和 (空间滤波Spatial Filtering) 模糊集合为处理不严密信息提供了一种形式. 首先,需要将输入量折算为隶属度,这个 ...
- Android学习笔记之使用百度地图实现Poi搜索
PS:装个系统装了一天.心力憔悴.感觉不会再爱了. 学习内容: 1.使用百度Map实现Poi搜索. 2.短串分享 3.在线建议查询 百度地图的研究也算是过半了.能够实现定位,实现相关信息的搜索,实 ...
- “康园圈--互联网+校园平台“项目之sprint2
一.sprint2任务列表 1.部署框架,并上传代码到github. 2.原型设计 * 设计首页界面原型(包括功能公告.快速通道等展示栏) * 设计店铺浏览页面原型 * 设计店内浏览页面原型 * 设计 ...
- SQL Server 文件和文件组
文件和文件组简介 在SQL Server中,数据库在硬盘上的存储方式和普通文件在Windows中的存储方式没有什么不同,仅仅是几个文件而已.SQL Server通过管理逻辑上的文件组的方式来管理文件. ...
- ubuntu 14.04 64位安装bigbluebutton
BigBlueButton 是一个使用 ActionScript 开发的在线视频会议系统或者是远程教育系统,主要功能包括在线PPT演示.视频交流和语音交流,还可以进行文字交流.举手发言等功能,特别适合 ...
- 通过发布项目到IIS上,登录访问报系统找不到System.Web.Mvc
我发布项目到IIs,通过IIS的端口来访问直接下面的错误
- 关于spring配置文件properties的问题
我遇到的问题是我将properties放在src下面的包中不能被spring扫描到,会报配置文件找不到的错误.但是如果放在src目录下就能够被spring扫描到,现在还不知道为什么这样,记个笔记,留到 ...
- mybatis generator with oracle
1.generator.xml <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generat ...
- couchbase单向同步
我们知道,couchbase默认情况下就是N主的HA模式,bucket同时存储在多个节点中.如下所示: 但事实上,有些时候我们希望某些节点只能读,不能写以避免各种副作用以及分布式系统下出于管理和安全性 ...
- [C#]多线程下载
发现电脑里以前编写的下载程序... 做个记录,那时做的挺匆忙的,没用委托,通过公开出窗体来修改下载进度,做的比较乱... ==!! 程序具体功能(流程): 1.检测系统托盘图标内的进程名是否符合要求 ...