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. 1 Servlet开篇准备

    作者:禅楼望月(http://www.cnblogs.com/yaoyinglong) 1. HTTP协议 HTTP协议是TCP/IP协议的上层协议.TCP负责确保从一个网络节点向另一个网络节点发送的 ...

  2. C#语法糖之 ReflectionSugar 通用反射类

    用法很简单: ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒 ,可以不填默认不缓存 rs.有嘛点嘛   性能测试: 性能测试类源码: ht ...

  3. Html5+css3+angularjs+jquery+webAPi 开发手机web(一)

    前言 随着浏览器的发展 HTML5+CSS3 的使用也越来越广泛,一直想学这个,想学那个折腾下来几乎没学到什么东西.工作经验告诉我,要掌握一门技术,就需要在项目中去磨练, 所以我就准备开发一个手机端的 ...

  4. [操作系统实验lab4]实验报告

    实验概况 在开始实验之前,先对实验整体有个大概的了解,这样能让我们更好地进行实验. 我们本次实验需要补充的内容包括一整套以sys开头的系统调用函数,其中包括了进程间通信需要的一些系统调用如sys_ip ...

  5. 扩展KMP --- HDU 3613 Best Reward

    Best Reward Problem's Link:   http://acm.hdu.edu.cn/showproblem.php?pid=3613 Mean: 给你一个字符串,每个字符都有一个权 ...

  6. 【WP8.1】富文本

    之前写过一篇WP8下的富文本的文章,但是写的不是很好,整理了一下,分享一下WP8.1下的富文本处理 富文本处理主要是对表情和链接的处理,一般使用RichTextBlock进行呈现 问题说明: 由于Ri ...

  7. Web前端测试题

    JS题目: 在JavaScript中( )方法可以对数组元素进行排序. A. add()B. join()C. sort()D. length() 答案:http://hovertree.com/ti ...

  8. [持续更新] 文章列表 last updated SEP 18, 2016

    1.前端 HTML5快速学习二 Canvas@20141125 HTML5快速学习一@20141122 2.ASP.NET(MVC) MVC5+EF6 入门完整教程14--动态生成面包屑@201608 ...

  9. 单例(C#版)

    单例: 一个类只有一个实例.巧妙利用了编程语言的一些语法规则:构造函数private, 然后提供一个public的方法返回类的一个实例:又方法和返回的类的实例都是static类型,所以只能被类所拥有, ...

  10. sql 随机抽取几条数据的方法 推荐

    传说用这个语句管用:select top 5 * from tablename order by newid() 我放到sql的查询分析器里去执行果然管用,随机抽取5条信息,不停的换,结果我应用到程序 ...