Android个人每天总结.doc(day05网络应用)

来源:互联网 发布:淘宝宝贝设置价格区间 编辑:程序博客网 时间:2024/06/06 03:30

作者:韩亚飞_yue31313_韩梦飞沙 QQ:313134555


鉴于 这个文件,还是保存的好。 所以等下把这个保存到网盘。  不删除。

day05网络应用

Ø 网络应用

一、定义:

就是安卓应用从web服务器上获得数据

二、怎么用?

(一)收网络文字

              创建一个URL对象

              使用一个URL获得一个链接用openConnection()方法

              设置请求方式,请求头,请求行....可省略

              HttpURLConnectin的setConnectTimeOut(毫秒值)设请求超时间.

              获取服务器数据 conn.getResponseCode().获得响应码

              判断响应码是否是正常200,如果是其它,抛一个异常.

              异常分给自已看和给用户看,不同的处理

              conn.getInputStream获得输入流

              定义一个字节缓冲流去接收输入流数据

              将数据转成字符串返回

              INTETNET权限,告诉用户这个应用要上网.

              main.xmlrTextView上加ScrollView属性,垂直拖动.

              HorizontalScrollView属性:可以水平拖动.

              模拟器访问要插网线.因为是模拟外部访问,要在一个网络坏境中,才能访问

用资源地址:

 String address = "http://192.168.1.111:8080/webdemo/blogs.xml";

URL url= new URL(address);---用网址构造Url

HttpURLConnection conn =(HttpURLConnection) url.openConnection();

HttpURLConnection conn = getConnectin(address);

      conn.setConnectTimeout(5000);

      intcode=conn.getResponseCode();

      if (code==200) {

        InputStream in=conn.getInputStream();

ByteArrayOutputStream bos=new ByteArrayOutputStream();

      byte[] b=newbyte[1024];

      int len=-1;

      while((len=in.read(b))!=-1){

        bos.write(b, 0, len);

      }

      byte[] bb=bos.toByteArray();

Strings=new String(bb);

 

      }

      throw new NetworkErrorException("sorry无法访问服务器:"+code);

   }

 

 

(二)收图片且实现缓存

ImageView:图片设置需要一个bitmap对象

看有没有一个Bitmap构造方法将字节变成bitmap

要么静态方法,要么构造方法,要么工厂去得到一个对象,这是一个思路.

获得URL--获得连接--用连接构建输入流

把输入流的数据输出到字节缓冲流中,并转换成字节数组

用输入字节数组转构造bitmap,返回

实现图片缓存

http默认缓存的思路:第一次访问后,浏览器会自动缓存,再访问过去时,

就会把最后修改时间时间与服务器比对.不变化则发304.变化则,200

 

要获得文件及最后修改时间

上下文有一个getCacheDir()方法获得缓存文件路径

用文件路径及文件名获得文件

用conn的setIf..方法发送缓存时间 --服务器跟据这个判断是回304还是200

获得响应码

判断哪果是200则重新请求 并把图片文件保存在缓存中(用一个线程去做,省时间)

304则从本地缓存中读取文件显示出来

 

public BitmapgetBitmap(String address)throws Exception {

      URL url= new URL(address);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

              //用链接名及缓存路径构建File

File cacheFile=newFile(context.getCacheDir(),URLEncoder.encode(portrait));

//判断缓存文件是否在缓存中存在,存在,则获取文件最后的修改时间并作为请求头发给web服务器

      if (cacheFile.exists()) {

        conn.setIfModifiedSince(cacheFile.lastModified());

      }

              //设定文件最大的响应等待时间

      conn.setConnectTimeout(3000);

//获取响应码,如为200,则表示本地没有缓存文件或有但资源文件已更新,则获取图片资源,并缓存到本地

      intcode=conn.getResponseCode();

        if (code==200) {

则获取图片资源,

           InputStreamin=conn.getInputStream();

           ByteArrayOutputStreambos=newByteArrayOutputStream();

           byte[] b=newbyte[1024];

           int len=-1;

           while((len=in.read(b))!=-1){

              bos.write(b, 0,len);

           }

           byte[] bb=bos.toByteArray();

                            //用字节数组生成Bitmap对象

Bitmap bm=BitmapFactory.decodeByteArray(bb,0, bb.length);

                            //且把bitmap存在本地缓存中

bm.compress(CompressFormat.JPEG, 100, new FileOutputStream(cacheFile));

           return bm;

                            //如果是返回的304,那么表示web服务器资源文件没有更新,则读本地缓存的图片资源

        }else if(code==304){

                            //用文件的绝对路径.

           return BitmapFactory.decodeFile(cacheFile.getAbsolutePath());

      }

        throw new NetworkErrorException("连接出错:" + code);

   }

(三)xml的网络读取

相对布局之图片按比例缩放adjustViewBounds="true"

#FFFFFF在#号后加两个数字表示透明度.

图片命名要符合java规则,比如不能以数字开头.

工程刷新,fix,F5..

获得xml从服务器---在用机上用ListView显示

用用address获得URL--用url获得HttpConnection--获得响应吗码

202--获得输入流-解析xml--把xml数据存入bean中--把bean存入list

将list中的数据变成一个ItemView Text处理service

做一个图片处理service

实现baseAdaper

抓异常尽量小,就是让一个功能显示不了,另一个也能显示

 

异步线程显示图片(或比较耗资源)

用线程启动

(四)Json解析js资源文件

1.       定义及作用:

JSONArray用于解析js资源文件

js资源文件就是JavaScript数组--相对于xml比较简洁

以下就是js资源文件的格式

[ {

       portrait: "http://192.168.1.111:8080/webdemo/portrait1.jpeg",

       name: "蒋坤",

       content: "好像双系统不那么好Ghost啊!",

       pic: null,

       from: "来自 QQ空间说说"

}, {

       portrait: "http://192.168.1.111:8080/webdemo/portrait3.jpeg",

       name: "各种诱惑美食",

       content: "宫廷桂花糕, 好正点!!",

       pic: "http://192.168.1.111:8080/webdemo/content1.jpeg",

       from: "来自 腾讯微博"

} ];

2.       怎么用?

JSONArray可以将字符串封装成一个json数组

遍历得到一个个JSONObject对象用arr.getJSONObject(i)

用json对象方法getString("元素名")得到各个元素值添加到bean中

注:getString得到为null的元素的值是:"null"字符串

     

              通过方法获取js文件输入流in,把输入流变成字符串

ByteArrayOutputStream bos=new ByteArrayOutputStream();

      byte[] b=newbyte[1024];

      int len=-1;

      while((len=in.read(b))!=-1){

        bos.write(b, 0, len);

      }

      byte[] bb=bos.toByteArray();

Strings=new String(bb);

              //用字符串构造JSONArray对象

      JSONArray json=new JSONArray(s);

              //解析字符串存入对象中

      for (int i = 0; i <json.length(); i++) {

        JSONObjectobj=json.getJSONObject(i);

        Weibo wb=new Weibo();

        wb.setPortrait(obj.getString("portrait"));

        wb.setName(obj.getString("name"));

        wb.setContent(obj.getString("content"));

        wb.setPic(obj.getString("pic"));

        wb.setFrom(obj.getString("from"));

        list.add(wb);

      }

 

(五)发送get请求

其实就是把数据用?连接到URL地址后发给服务器

如:http://www.web.com?name=aaa&age=17

设定提交方式:conn.setRequestMethod("GET");

注意中文编码问题:在servlet中把获得的数据用iso8859-1解码,再utf-8编码

在手机端也要用url编码:用URLEconde.enconde(String)

手机--servlet的编码过程

手机上的字符 ---utf-8 --- 字节 --->tomcat--- 字节 ---iso8859-1 --- iso8859-1 --- 字节 --- utf-8 --- 字符

public boolean get(String username, Stringpassword) throws Exception {

              username = URLEncoder.encode(username,"UTF-8");      

// 传入中文和特殊字符时, 如果不进行编码, 会出错

              password= URLEncoder.encode(password, "UTF-8");

              Stringparams = "username=" + username + "&password=" +password;

             

              URLurl = new URL(address + "?" + params);

              HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

              conn.setConnectTimeout(3000);

              conn.setRequestMethod("GET");

             

              returnconn.getResponseCode() == 200;

       }

(六)发送post请求

这三个请求行要设置:

Content-Type和host与content-Lenth

用conn的setRequestProperty("属性名","属性值");

确认输出conn.setDoOutput(true)方法

用输出流输出:conn.getOutputStrem.write(byte[]);

发xml,访问webService,且得到数据

 

public boolean post(String username, Stringpassword) throws Exception {

              username= URLEncoder.encode(username, "UTF-8");      

// 传入中文和特殊字符时, 如果不进行编码, 会出错

              password= URLEncoder.encode(password, "UTF-8");

              Stringparams = "username=" + username + "&password=" +password;

             

              URLurl = new URL(address);

              HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

              conn.setConnectTimeout(3000);

              conn.setRequestMethod("POST");

             

              conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

              conn.setRequestProperty("Content-Length",params.getBytes().length + "");

              conn.setRequestProperty("Host","192.168.1.253:8080");

              conn.setDoOutput(true);

              conn.getOutputStream().write(params.getBytes());

             

              returnconn.getResponseCode() == 200;

       }

(七)发xml访问webService:

是发布在网络上的API,可以通过发送XML调用,WebService返回结果也是XML数据

WebService没有语言限制,只要可以发送XML数据和接收XML数据即可

http://www.webxml.com.cn 网站上提供了一些WebService服务,我们可以对其进行调用

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo中提供了电话归属地查询的使用说明

查到数据xml格式及host及web地址

URL=host+web应用名

用URL网络发送数据

定义xml,用流读出xml成一个String

用电话号码替换xml里的num

用post方式发送到webService,记住post有三个必须发的请求行.

如果返回202,则conn.getInputStream()获得输入流

解析xml得到归属地String

给网络权限

归属地代码示例:

public String query(String num) throwsException {

              InputStreamin =QueryService.class.getClassLoader().getResourceAsStream("template.xml");

              Stringdata = new String(Util.read(in));       //读取模板文件, 得到要发送的xml

              in.close();

              data= data.replace("phoneNum", num);             //用号码替换占位符

             

              URLurl = newURL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");             // 创建Webservice的Url地址

              HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

              conn.setConnectTimeout(3000);

              conn.setRequestMethod("POST");

              //设制三个请求头参数

              conn.setRequestProperty("Host","webservice.webxml.com.cn");

              conn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");

              conn.setRequestProperty("Content-Length",data.getBytes().length + "");

              conn.setDoOutput(true);

              conn.getOutputStream().write(data.getBytes());

             

              intcode = conn.getResponseCode();

              if(code == 200) {

                     returnparseAddress(conn.getInputStream());              //获取服务端发回的XML, 解析出地址

              }

              thrownew NetworkErrorException("服务器出错: " + code);

       }

 

       privateString parseAddress(InputStream inputStream) throws Exception {

              XmlPullParserparser = Xml.newPullParser();

              parser.setInput(inputStream,"UTF-8");

              for(int type = parser.getEventType(); type != XmlPullParser.END_DOCUMENT; type =parser.next()) {

                     if(type == XmlPullParser.START_TAG &&parser.getName().equals("getMobileCodeInfoResult")) {

                            returnparser.nextText();

                     }

              }

              returnnull;

       }

 

}

(八)文件上传:

servlet中定义表单

导包:两个upload与io包

判断是否是以上传方式发送的post请求

如果是用upload解析

得到对象,把数据解析成一个List<FileItem>

遍历

手机上传:

拼接post请求

定义分隔符

得到要上传的文件file

开启与服务器的连接

获得字符缓冲sb

用sb拼接post请求

文件上传代码示例:

public boolean upload(String username,String password, String filepath) throws Exception {

              Stringboundary = "---------------------------7dc36b152804a8";  // 分割线

              Filefile = new File(filepath);                            //要上传的文件

              URLurl = new URL(address);                                  //用来开启连接

              StringBuildersb = new StringBuilder();             // 用来拼装请求

 

              //username字段

              sb.append("--"+ boundary + "\r\n");

              sb.append("Content-Disposition:form-data; name=\"username\"" + "\r\n");

              sb.append("\r\n");

              sb.append(username+ "\r\n");

 

              //password字段

              sb.append("--"+ boundary + "\r\n");

              sb.append("Content-Disposition:form-data; name=\"password\"" + "\r\n");

              sb.append("\r\n");

              sb.append(password+ "\r\n");

 

              //文件部分

              sb.append("--"+ boundary + "\r\n");

              sb.append("Content-Disposition:form-data; name=\"file\"; filename=\"" + filepath +"\"" + "\r\n");

              sb.append("Content-Type:application/octet-stream" + "\r\n");

              sb.append("\r\n");

 

              //将开头和结尾部分转为字节数组

              byte[]before = sb.toString().getBytes("UTF-8");

              byte[]after = ("\r\n--" + boundary +"--\r\n").getBytes("UTF-8");

             

              //打开连接, 设置请求头

              HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

              conn.setConnectTimeout(3000);

              conn.setRequestMethod("POST");

              conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);

              conn.setRequestProperty("Content-Length",before.length + file.length() + after.length + "");

              conn.setRequestProperty("HOST","192.168.1.253:8080");             

              conn.setDoOutput(true);

 

              //获取输入输出流

              OutputStreamout = conn.getOutputStream();

              InputStreamin = new FileInputStream(file);

 

              //将开头部分写出

              out.write(before);

 

              //写出文件数据

              byte[]buf = new byte[1024];

              intlen;

              while((len = in.read(buf)) != -1)

                     out.write(buf,0, len);

 

              //将结尾部分写出

              out.write(after);

             

              in.close();

              out.close();

              returnconn.getResponseCode() == 200;

       }

}

 

(九)文件下载:

获得输入流,写入到

把web.xml中的文件数据类型放入sharedPreference中.

文件下载代码示例:

public static void main(String[] args)throws Exception {

              URLurl = new URL("http://192.168.1.253:8080/15.Web/FeiQ.exe");

              HttpURLConnectionconn = (HttpURLConnection) url.openConnection();

              conn.setConnectTimeout(3000);

             

              intcode = conn.getResponseCode();

              if(code == 200) {

                     InputStreamin = conn.getInputStream();

                     OutputStreamout = new FileOutputStream("F:/Download/FeiQ.exe");

                     byte[]buffer = new byte[1024 * 100];

                     intlen;

                     while((len = in.read(buffer)) != -1)

                            out.write(buffer,0, len);

                     in.close();

                     out.close();

              }

       }


0 0
原创粉丝点击