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. java io系列06之 序列化总结(Serializable 和 Externalizable)

    本章,我们对序列化进行深入的学习和探讨.学习内容,包括序列化的作用.用途.用法,以及对实现序列化的2种方式Serializable和Externalizable的深入研究. 转载请注明出处:http: ...

  2. 美了美了!22款精美的 iOS 应用程序图标模板

    22款制作精美的 iOS 应用程序图标设计作品,遵循图形设计的现代潮流,所有图标都非常了不起,给人惊喜.通过学习这些移动应用程序图标,设计人员可以提高他们的创作,使移动用户界面看起来更有趣和吸引人. ...

  3. XPATH使用总结

    最近公司里需要写一些爬虫项目,所以去接触学习了xpath的内容.在w3c上给出了xpath的语法,但是我感觉不全,而且讲得也不详细,我又去网上找了一些文章,总结一下. 这几个都是比较常用的,能解决基本 ...

  4. 流行的ios开源项目

    本文介绍一些流行的iOS的开源项目库 1.AFNetworking 更新频率高的轻量级的第三方网络库,基于NSURL和NSOperation,支持iOS和OSX.https://github.com/ ...

  5. 重构第22天 分解方法(Break Method)

    理解:如果一个功能,里面比较复杂,代码量比较多,我们就可以把这个功能分解成多个小的method,每个方法实现该功能的一个小小的部分,并且方法命名成容易理解,和方法内容相关的名称,更有助于维护和可读性提 ...

  6. C#设计模式——访问者模式(Visitor Pattern)

    一.概述由于需求的改变,某些类常常需要增加新的功能,但由于种种原因这些类层次必须保持稳定,不允许开发人员随意修改.对此,访问者模式可以在不更改类层次结构的前提下透明的为各个类动态添加新的功能.二.访问 ...

  7. 若干道Swift面试题

    1,说说你认识的Swift是什么?Swift是苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C共同运行于MAC OS和iOS平台,用于搭建基于苹果平台的应用程序. ...

  8. vs2012中怎样设为起始页,怎样取消

    把你要设为起始页的文件右键选择为起始页,如下:

  9. springMVC图片文件上传功能的实现

    在工程依赖库下添加文件上传jar包 commons-fileupload-1.2.2.jar commons-io-2.4.jar 2.jsp页面设置form表单属性enctype 在表单中上传图片时 ...

  10. PHP遍历目录四种方法

    学习SPL的时候,遇到了DirectoryIterator这个目录类,谢了一下遍历目录的方法.于是总结一下遍历目录的四种写法 如下: <?php /* * 方法一:利用SPL的目录类,这个很简单 ...