Develop network with HttpURLConnection & HttpClient.html
HttpURLConnection is lightweight with HttpClient.java
So normally, you just need HttpURLConnection.android
NetWork is a timer wast task, so it is better doing this at asynctask.web
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.app
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. async
One is loading with:ide
mContent.loadData(result, "text/html; charset=UTF-8", null);
and another one is :post
mWebView.loadUrl(stringurl);
as result is loadUrl is very fast, but you can not filter the result.ui
and for more case, we using network to connect with server.this
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);