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的更多相关文章

  1. 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 ...

  2. 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 ...

  3. P2746 [USACO5.3]校园网Network of Schools// POJ1236: Network of Schools

    P2746 [USACO5.3]校园网Network of Schools// POJ1236: Network of Schools 题目描述 一些学校连入一个电脑网络.那些学校已订立了协议:每个学 ...

  4. 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 ...

  5. android network develop(3)----Xml Parser

    Normally, there are three type parser in android. Xmlpullparser, DOM & SAX. Google recomand Xmlp ...

  6. android network develop(2)----network status check

    Check & Get network status Normally, there will be two type with phone network: wifi & mobil ...

  7. Android中通过GPS或NetWork获取当前位置的经纬度

    今天在Android项目中要实现一个通过GPS或NetWork来获取当前移动终端设备的经纬度功能.要实现该功能要用到Android Framework 中的 LocationManager 类.下面我 ...

  8. [Android]Volley源代码分析(叁)Network

    假设各位看官细致看过我之前的文章,实际上Network这块的仅仅是点小功能的补充.我们来看下NetworkDispatcher的核心处理逻辑: <span style="font-si ...

  9. Android 使用 NYTimes Stores 缓存 network request

    NYTimes Stores 是一个缓存库,在 2017年的 AndroidMakers 大会上被介绍过. https://github.com/NYTimes/Store 实现一个 Disk Cac ...

随机推荐

  1. LeetCode——Merge k Sorted Lists

    Discription: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its ...

  2. Direct3D11学习:(二)基本绘图概念和基本类型

    转载请注明出处:http://www.cnblogs.com/Ray1024   一.概述 在正式开始学习D3D11之前,我们必需首先学习必要的基础知识. 在这篇文章中,我们将介绍一下Direct3D ...

  3. python网络编程socket /socketserver

    提起网络编程,不同于web编程,它主要是C/S架构,也就是服务器.客户端结构的.对于初学者而言,最需要理解的不是网络的概念,而是python对于网络编程都提供了些什么模块和功能.不同于计算机发展的初级 ...

  4. Sprint 3计划

    一.计划目标: 1.完成基本的首页面的信息查询功能 2.学生家教用户注册和登录,将信息存储到数据库 3.完成家教的资格评定设定和个人教学内容备份信息 二.燃尽图 三.项目具体工作细则 待明天工作会议分 ...

  5. HNU 13308 Help cupid

    Help cupid Problem's Link: http://acm.hnu.cn/online/?action=problem&type=show&id=13308&c ...

  6. vs.net_2003 下载 虽然是老古董了,但还是很有用的。

    系统要求 支持的操作系统: Windows 2000; Windows NT; Windows Server 2003; Windows XP 以下VS2003的下载链接: http://bcsoft ...

  7. 甲骨文白桃花心木P6 EPPM 8.2项目点提供样本

    甲骨文白桃花心木样例代码 除非明确确定,这里的示例代码不是认证或Oracle支持;它只是用于教育或测试的目的. 你必须接受 许可协议下载此示例代码.  接受 许可协议 |  下降 许可协议   的名字 ...

  8. [迷宫中的算法实践]迷宫生成算法——递归分割算法

    Recursive division method        Mazes can be created with recursive division, an algorithm which wo ...

  9. 实例对比剖析c#引用参数的用法

    c#引用参数传递的深入剖析值类型的变量存储数据,而引用类型的变量存储对实际数据的引用.(这一点很重要,明白了之后就能区分开值类型和引用类型的差别) 在参数传递时,值类型是以值的形式传递的(传递的是值, ...

  10. Linux守护进程实现程序只运行一次

    1.守护进程 守护进程(Daemon)是一种运行在后台的特殊进程,它独立于控制终端并且周期性的执行某种任务或等待处理某些发生的事件. 2.让程序只运行一次 如果让程序只运行一次,有很多方法,此处的一种 ...