zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    【Linux设备驱动程序】Chapter 2
    【Linux设备驱动程序】Chapter 1
    sed 命令多行到多行的定位方式
    chmod 与大写 X
    C 语言中模板的几种实现方式
    /etc/default/grub 部分配置选项设置
    fcitx error
    QT5学习过程的小问题集锦
    Qt4编码
    Qt MainWindow结构
  • 原文地址:https://www.cnblogs.com/deman/p/4627318.html
Copyright © 2011-2022 走看看