网络编程

一、网络连接
     ConnectivityManager负责管理所有的链接服务
      *、查看网络状态NetworkInfo
            通过ConnectivityManager获得
             用来检测当前网络类型,用来检测当前网络状态。
             eg:
                    //得到一个网络管理类的对象
              ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.           CONNECTIVITY_SERVICE);
            //获得网络的相关信息对象,用NetWorkInfo,获得活着的网络连接信息。
             //如果手机是飞行模式,则返回的ni为空
              NetworkInfo ni=cm.getActiveNetworkInfo();
            //获得网络连接的信息,与networkinfo中的状态常量比较,则得到当前网络连接的状    态。
                 if(ni.getState().equals(NetworkInfo.State.CONNECTING)){
             }

     获取网络数据
        *、如同对文件的读写来操作网络的访问,InputStream\OutputStream
        *、HttpURLConnection可以用来发送接收网络数据
                 HttpURLCOnnection实例调用getInputStream可以获得InputStream
        *、创建步骤:
            1、 创建URL     URL url =new URL (“网络地址”);  创建访问的地址
            2、  创建HttpURLConnection链接,根据链接获得输入\输出
                 connect = (HttpURLConnection)url.openConnection();
            3、获得输入暑促,
                 InputStream input = connection.getInputStream();
        *、创建网络访问要添加网络访问权限
             <uses-permission  android:name="android.permission,INTERNET"/>

      注意:网络方法总是存在阻塞的可能
              *、需要放到主线程之外操作,否则可能抛出异常

            eg:     class MyAsyncTask extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... arg0) {
        try {
        URL url = new URL(URL_WEATHER);
        URLConnection connection = (URLConnection) url.openConnection();
        InputStream is = connection.getInputStream();
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while ((i=is.read())!=-1) {
          sb.append((char)i);

        }
        return sb.toString();
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return null;
    }

    @Override
    protected void onPostExecute(String result) {

      super.onPostExecute(result);
      textView = (TextView)findViewById(R.id.textView1);
         textView.setText(result);
    }
  }

HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
3)设置容许输出:conn.setDoOutput(true);
4)设置不使用缓存:conn.setUseCaches(false);
5)设置使用POST的方式发送:conn.setRequestMethod("POST");
6)设置维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");
7)设置文件字符集:conn.setRequestProperty("Charset", "UTF-8");
8)设置文件长度:conn.setRequestProperty("Content-Length", String.valueOf(data.length));
9)设置文件类型:conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

  *、更健壮的HTTP协议
      1、请求被封装为HttpGet/HttpPost
      2、执行体被封装为 HttpClient 用于执行请求。
      3、应答被封装为
            HttpResponse代表服务器响应
            HttpConnext保持通讯状态信息
            HttpEntity 响应传回的数据
        得到的数据经常会出现乱码,这里我们可以使用一个类确定得到数据的编码
                   HttpGet get  = new HttpGet(URL );
            HttpClient client = new DefaultHttpClient();
               HttpResponse response = client.execute(get);
            String message = EntityUtils.toString(response.getEntity(), "UTF-8");
            这里可以直接得到一个数据,转换为String类型,和可以确定编码

                eg:
                        class MyAsyncTask extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... arg0) {
        try {

          HttpGet get = new HttpGet(URL_WEATHER);
          HttpClient client =  new DefaultHttpClient();
          //得到一个网络访问的回复,回复包含很多信息
          HttpResponse hr =   client.execute(get);
          //判断网络回复的状态信息,
          if (hr.getStatusLine().getStatusCode()==HttpStatus.SC_OK) {
          //网络回复的信息中用getEntity函数可以得到网络访问回复的数据,getContent
            //函数可以得到一个输入数据流。
          InputStream is=  hr.getEntity().getContent();
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while ((i=is.read())!=-1) {
          sb.append((char)i);

        }
        return sb.toString();
          }
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      return null;
    }

    @Override
    protected void onPostExecute(String result) {

      super.onPostExecute(result);
      textView = (TextView)findViewById(R.id.textView1);
         textView.setText(result);
    }
  }


二、WebView
        *、使用的时候要添加网络访问权限
        *、添加WebView 控件,
        *、编写代码:
        WebView webView = (WebView)findViewById(R.id.webView1);
       webView.loadUrl("http://view.news.qq.com/original/intouchtoday/n3371.html");
       注意LoadUrl中的字符串,好多页面上显示的路径衡多在webView中都打不开。

  运行JavaScript:
        可以在网页中调用android的功能,设备信息查询,调用对话框。
    *、首先使用WebView允许执行JavaScript
         getSettings可以获得WebView的设置
    *、将javaScript代码绑定到android中的代码
        通过addJavascriptInterface()绑定两者
        在android代码中实现对应的接口给JavaScript调用
        在Script中明确调用接口

三、JSON解析

  *、JSON  一种轻量级的数据交换格式
      可以使用JSON传输数据类型,基于纯文本的数据格式
          String number  boolean   数组   复杂的 Object类型
  *、JSON的格式
         键值对的格式,以冒号间隔,值用双引号
         {"name":"zhangsan","age":"21"}
         值可以是另一个键值对的集合
         {"name":{"city":"shanghai","cityid",21""}}
  *、JSON的解析实现
       1、 JSONObject代表了一个带解析的兼职对集合,参数可以是一个JSON文件
              或者JSON格式的字符串
            JSONObject jOBj = new JSONObject(data);
       2、通过get方式获取键值对中的values的值,参数为键
            String name = jOBj.getString("name");
            int age = jOBj.getInt("age");
              如果value是对象,用对象接受,据需解析
                 JSONObject obj = jOBj.getJSONObject("xxx");
              如果value是数组,用数组接受,继续解析
                  JSONArray arr = jOBj.getJSONArray("xxx");
                    arr相当于一个数组,获得的时候就从下标获得
                  JSONObject job = arr.get(0); 再从JSONObject中解析,一层层的解析

eg:
package com.tian.com.work12_13_third;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    final  String BEIJIN= "http://api.k780.com:88/?app=weather.future&weaid=1&appkey=12445&sign=" +
            "52e38d92690b729a65ed10871a604d56&format=json";
    final  String SHANGHAI="http://api.k780.com:88/?app=weather.future&weaid=36&appkey=" +
            "12445&sign=52e38d92690b729a65ed10871a604d56&format=json";

     List<String> list = new ArrayList<String>();
     ListView show ;
     Spinner city ;
     ArrayAdapter<String> adapter;
    TextView  Tweek ,Tweather,Ttemperature, Twind;
    ImageView Ibitmap ;

    List<Weather> wlist = new ArrayList<Weather>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super .onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //关联控件
        city = (Spinner)findViewById(R.id.spinner);
       // show = (ListView)findViewById(R.id.listView);
       // textView = (TextView)findViewById(R.id.textView);
        list.add("北京");
        list .add("上海");
        //和ListView相似,用list作为数据源,做一个适配器类对象
        adapter = new ArrayAdapter<String>( this,android.R.layout. simple_spinner_item, list );
        //适配器spinner可以设置显示样式。
        adapter.setDropDownViewResource(android.R.layout. simple_spinner_dropdown_item);
        //为spinner添加适配器,显示城市
        city.setAdapter(adapter);
        //为spinner的每一项添加一个响应
        city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position== 0) {
                          wlist.clear();
                        new MyAsyncTask().execute( BEIJIN);

                }else {
                    wlist.clear();
                        new MyAsyncTask().execute( SHANGHAI);
                    }

                }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    StringBuffer sb ;
    class  MyAsyncTask extends AsyncTask<String,Void,Void>{

        Bitmap bitmap;
        @Override
        protected Void doInBackground(String... params) {
            Log.i( "tian",params[0 ]);
            HttpGet get  = new HttpGet(params[ 0]);
            HttpClient client = new DefaultHttpClient();

           try {
               //通过HttpResponse获得数据
               HttpResponse response = client.execute(get);
               //使用EntityUtils.toString 方法转化获得数据的格式
               String message = EntityUtils.toString(response.getEntity(), "UTF-8");
               //Log.i("tian",message);
               //
               JSONObject job = new JSONObject(message);
               JSONArray ja = job.getJSONArray( "result");
               for (int i = 0; i < ja.length(); i++) {
                   JSONObject jobday = ja.getJSONObject(i);
                   //获得星期几
                   String week = jobday.getString("week");
                   //获得天气
                   String weather = jobday.getString("weather");
                   //获得图片的地址,并得到一个Bitmap对象
                   String bitmapurl = jobday.getString("weather_icon");
                   URL url = new URL(bitmapurl);
                   URLConnection connection = url.openConnection();
                   InputStream is = connection.getInputStream();
                    bitmap = BitmapFactory. decodeStream(is);
                   //获得温度信息
                   String temperature = jobday.getString("temperature");
                   //获得风力信息
                   String wind = jobday.getString("wind");
                  Weather weather1 = new Weather(week,weather, bitmap,temperature,wind);
                   wlist.add(weather1);

               }
               Log.i ("tian" , wlist.size()+"");

               }catch(MalformedURLException e){
                   e.printStackTrace();
               }catch(IOException e){
                   e.printStackTrace();
               }catch(JSONException e){
                   e.printStackTrace();
               }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            show = (ListView)findViewById(R.id.listView);
            show.setAdapter(new MyAdapter());
            super.onPostExecute(aVoid);
        }
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return wlist.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           // final  Weather weather =wlist.get(position);
            convertView = LayoutInflater. from(MainActivity.this).inflate(R.layout. weather,parent,false );
            Tweek = (TextView)convertView.findViewById(R.id. week);
            Tweather= (TextView)convertView.findViewById(R.id. weather);
            Ibitmap = (ImageView)convertView.findViewById(R.id. weather_icon);
            Ttemperature = (TextView)convertView.findViewById(R.id. temperature);
            Twind=(TextView)convertView.findViewById(R.id. wind);
            Tweek.setText(wlist.get(position).getWeek());
            Tweather.setText(wlist.get(position).getWeather());
            Ibitmap.setImageBitmap(wlist.get(position).getBitmap());
            Ttemperature.setText(wlist.get(position).getTemperature());
            Twind.setText(wlist.get(position).getWind());

            return convertView;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值