基于安卓平台的程序设计:网络通讯1_第1页
基于安卓平台的程序设计:网络通讯1_第2页
基于安卓平台的程序设计:网络通讯1_第3页
基于安卓平台的程序设计:网络通讯1_第4页
基于安卓平台的程序设计:网络通讯1_第5页
已阅读5页,还剩53页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、1. 使用URL访问网络资源1) URL构造函数可以指定资源地址,如:URL url = new URL(/a.jpg);2) String getFile() 获取URL资源名String getHost() 获取URL 主机名 String getPath() 获取URL路径部分URLConnection openConnection ()返回连接对象InputString openStream() 打开URL链接,返回读取该URL资源的流1.1 使用URL读取网络资源(P489,URLTest)public class URLTest extends ActivityImageView

2、show;Overridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.main);show = (ImageView) findViewById(R.id.show);/ 定义一个URL对象try URL url = new URL(/attachments/”+ month_1008/20100812_7763e970f822325bfb019ELQVym8tW3A.png);/ 打开该URL对应的资源的输入流InputStr

3、eam is = url.openStream();/ 从InputStream中解析出图片Bitmap bitmap = BitmapFactory.decodeStream(is);/ 使用ImageView显示该图片show.setImageBitmap(bitmap);is.close();/ 再次打开URL对应的资源的输入流is = url.openStream();/ 打开手机文件对应的输出流OutputStream os = openFileOutput(crazyit.png, MODE_WORLD_READABLE);byte buff = new byte1024; int

4、 hasRead = 0;/ 将URL对应的资源下载到本地while(hasRead = is.read(buff) 0) os.write(buff, 0 , hasRead); is.close();os.close();catch (Exception e)e.printStackTrace();1.2 使用URLConnection提交请求(P492,GetPostTest)URL 的 openConnection()返回 URLConnection对象,以后可通过设置该对象的参数和请求属性,可以从远程读取数据,也可以向远程发送数据请求种类: Web 上最常用的两种 Http 请求就是

5、 Get 请求和 Post 请求。GET 从服务器上获取数据,这是最常见的请求类型。简单的参数通过URL地址发送每次在浏览器中输入 URL 打开页面时,就是向服务器发送一个 Get 请求。 Get 请求的参数是用问号追加到 URL 结尾,后面跟着用连接起来的名称值对。比如网址 /viewthread.php?tid=87813&id2=kk ,其中 tid ,id2为参数名, 87813,kk 为参数的值。通过 URL 可以看到中传递的参数。因此,相比于 Post ,它是不安全的POST可以传递复杂的数据,如表单。Post 的使用场合多是在表单提交的地方,因为和 Get 相比, Post 可以

6、发送更多的数据 Post 是通过 HTTP Post 机制,将表单内各个字段与其内容放置在 HTML Header 内一起传送到 ACTION 属性所指的 URL 地址。 和 Get 相比, Post 的内容是不会在 URL 中显现出来的,这多少是安全一些的。1.2 使用URLConnection提交请求(P492,GetPostTest)GetPostUtil.javapublic class GetPostUtil/* * 向指定URL发送GET方法的请求 * param url * 发送请求的URL * param params * 请求参数,请求参数应该是name1=value1&na

7、me2=value2的形式。 * return URL所代表远程资源的响应 */public static String sendGet(String url, String params)String result = ;BufferedReader in = null;tryString urlName = url + ? + params;URL realUrl = new URL(urlName);/ 打开和URL之间的连接URLConnection conn = realUrl.openConnection();/ 设置通用的请求属性conn.setRequestProperty(a

8、ccept, */*);conn.setRequestProperty(connection, Keep-Alive);conn.setRequestProperty(user-agent,Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1);/ 建立实际的连接conn.connect();/ 获取所有响应头字段MapString, List map = conn.getHeaderFields();/ 遍历所有的响应头字段for (String key : map.keySet() System.out.println(key + +

9、 map.get(key);/ 定义BufferedReader输入流来读取URL的响应in = new BufferedReader( new InputStreamReader(conn.getInputStream();String line;while (line = in.readLine() != null) result += n + line;catch (Exception e)System.out.println(发送GET请求出现异常! + e);e.printStackTrace();/ 使用finally块来关闭输入流finallytryif (in != null)

10、in.close();catch (IOException ex)ex.printStackTrace();return result;/* * 向指定URL发送POST方法的请求 * param url * 发送请求的URL * param params * 请求参数,请求参数应该是name1=value1&name2=value2的形式。 * return URL所代表远程资源的响应 */public static String sendPost(String url, String params)PrintWriter out = null;BufferedReader in = nul

11、l;String result = ;tryURL realUrl = new URL(url);/ 打开和URL之间的连接URLConnection conn = realUrl.openConnection();/ 设置通用的请求属性conn.setRequestProperty(accept, */*);conn.setRequestProperty(connection, Keep-Alive);conn.setRequestProperty(user-agent,Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1);/ 发送P

12、OST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);/ 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream();/ 发送请求参数out.print(params);/ flush输出流的缓冲out.flush();/ 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream();String line;while (line

13、 = in.readLine() != null)result += n + line;catch (Exception e)System.out.println(发送POST请求出现异常! + e);e.printStackTrace();/ 使用finally块来关闭输出流、输入流finallytryif (out != null)out.close();if (in != null)in.close();catch (IOException ex)ex.printStackTrace();return result;GetPostMain.javapublic class GetPost

14、Main extends ActivityButton get , post;EditText show;Overridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.main);get = (Button) findViewById(R.id.get);post = (Button) findViewById(R.id.post);show = (EditText)findViewById(R.id.show);get.setO

15、nClickListener(new OnClickListener()Overridepublic void onClick(View v)String response = GetPostUtil.sendGet(/dict/search,q=please&qs=n&form=CM&pq=please&sc=0-0&sp=-1&sk=);show.setText(response);/查必应词典);/在必应词典查单词 please 的URL是:/ /dict/search? q=please&qs=n&form=CM&pq=please&sc=0-0&sp=-1&sk=post.setOn

16、ClickListener(new OnClickListener()Overridepublic void onClick(View v)String response = GetPostUtil.sendPost(/login,user_id1=guowei&password1=123);/登录POJshow.setText(response););User ID:Password:RegisterString response = GetPostUtil.sendPost(/login,user_id1=guowei&password1=123);Post错误密码后:String res

17、ponse = GetPostUtil.sendPost(/login,user_id1=guowei&password1=XXXX);Post正确密码后:2 使用HTTP访问网络URLConnection的派生类 HttpURLConnection 也可以用来发送POST请求和GET请求2.1 多线程下载(P496,MultiThreadDown)创建URL对象,用getContentLength()获取资源大小,然后在本地磁盘创建同样大小的空文件,然后计算每条线程应该下载文件哪部分,再创建多个线程2.1 多线程下载(P496,MultiThreadDown)DownUtil.java 与A

18、ndroid无关public class DownUtil/ 定义下载资源的路径private String path;/ 指定所下载的文件的保存位置private String targetFile;/ 定义需要使用多少线程下载资源private int threadNum;/ 定义下载的线程对象private DownloadThread threads;/ 定义下载的文件的总大小private int fileSize;public DownUtil(String path, String targetFile, int threadNum)this.path = path;this.t

19、hreadNum = threadNum;/ 初始化threads数组threads = new DownloadThreadthreadNum;this.targetFile = targetFile;public void download() throws ExceptionURL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5 * 1000);conn.setRequestMethod(GET);conn.setR

20、equestProperty(Accept,image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*);conn.setR

21、equestProperty(Accept-Language, zh-CN);conn.setRequestProperty(Charset, UTF-8);conn.setRequestProperty(User-Agent,Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729);conn.setRequestP

22、roperty(Connection, Keep-Alive);/ 得到文件大小fileSize = conn.getContentLength();conn.disconnect();int currentPartSize = fileSize / threadNum + 1;RandomAccessFile file = new RandomAccessFile(targetFile, rw);/ 设置本地文件的大小file.setLength(fileSize);file.close();for (int i = 0; i threadNum; i+)/ 计算每条线程的下载的开始位置in

23、t startPos = i * currentPartSize;/ 每个线程使用一个RandomAccessFile进行下载RandomAccessFile currentPart = new RandomAccessFile(targetFile,rw);/ 定位该线程的下载位置currentPart.seek(startPos);/ 创建下载线程 threadsi = new DownloadThread(startPos, currentPartSize,currentPart);/ 启动下载线程threadsi.start();/ 获取下载的完成百分比public double ge

24、tCompleteRate()/ 统计多条线程已经下载的总大小int sumSize = 0;for (int i = 0; i threadNum; i+)sumSize += threadsi.length;/ 返回已经完成的百分比return sumSize * 1.0 / fileSize;private class DownloadThread extends Thread/ 当前线程的下载位置private int startPos;/ 定义当前线程负责下载的文件大小private int currentPartSize;/ 当前线程需要下载的文件块private RandomAc

25、cessFile currentPart;/ 定义已经该线程已下载的字节数public int length;public DownloadThread(int startPos, int currentPartSize,RandomAccessFile currentPart)this.startPos = startPos;this.currentPartSize = currentPartSize;this.currentPart = currentPart;Overridepublic void run()tryURL url = new URL(path);HttpURLConnec

26、tion conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5 * 1000);conn.setRequestMethod(GET);conn.setRequestProperty(Accept,image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap,

27、 application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*);conn.setRequestProperty(Accept-Language, zh-CN);conn.setRequestProperty(Charset, UTF-8);InputStream inStream = conn.getInputStream();/ 跳过startPos个字节,表明该线程只下载自己负责哪部分文件。inStream.skip(this.s

28、tartPos);byte buffer = new byte1024;int hasRead = 0;/ 读取网络数据,并写入本地文件while (length = 100) timer.cancel();, 0, 100););2.3 使用Apache Http Client (P501,HttpClientTest)为了处理session,Cookie等问题,可以使用 HttpClient,简单的Http客户端,但不能执行网页的 javascript,也不能解析网页Session: 在服务器端存放的用户的信息,比如登录以后,登录网页会在服务器端存放 session“username” =

29、 “xxxx”,此后在同一浏览器内访问的各个页面,启动时 都可以在服务器端通过关键字”username”获取session中存放的用户名Cookie:浏览器保存在客户端的临时信息2.3 使用Apache Http Client (P501,HttpClientTest)使用HttpClient: 创建 HttpGet对象发送Get请求创建 HttpPost对象发送Post请求HttpPost,HttpGet都有setParams可以设置请求参数HttpClient的excute(HttpUriRequest )可以发送请求,返回HttpResponse对象HttpResponse对象的 get

30、Entity可以获取 HttpEntity对象,内含服务器响应内容2.3 .1 HttpClient访问被保护资源 (P501,HttpClientTest)public class HttpClientTest extends ActivityButton get;Button login;EditText response;HttpClient httpClient;Overridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout

31、.main);/ 创建DefaultHttpClient对象httpClient = new DefaultHttpClient();get = (Button) findViewById(R.id.get);login = (Button) findViewById(R.id.login);response = (EditText) findViewById(R.id.response);get.setOnClickListener(new OnClickListener()Overridepublic void onClick(View v)/ 创建一个HttpGet对象HttpGet g

32、et = new HttpGet(8:8888/foo/secret.jsp);try/ 发送GET请求HttpResponse httpResponse = httpClient.execute(get);HttpEntity entity = httpResponse.getEntity();if (entity != null)/ 读取服务器响应BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent();String line = null;response.setText();whil

33、e (line = br.readLine() != null)/ 使用response文本框显示服务器响应response.append(line + n);catch (Exception e)e.printStackTrace(););login.setOnClickListener(new OnClickListener()Overridepublic void onClick(View v)final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);new AlertDialog.Builder

34、(HttpClientTest.this).setTitle(登录系统).setView(loginDialog).setPositiveButton(登录,new DialogInterface.OnClickListener()Overridepublic void onClick(DialogInterface dialog,int which)String name = (EditText) loginDialog.findViewById(R.).getText().toString();String pass = (EditText) loginDialog.findViewByI

35、d(R.id.pass).getText().toString();HttpPost post = new HttpPost(8:8888/foo/login.jsp);/ 如果传递参数个数比较多的话可以对传递的参数进行封装List params = new ArrayList();params.add(new BasicNameValuePair(name, name);params.add(new BasicNameValuePair(pass, pass);try/ 设置请求参数post.setEntity(new UrlEncodedFormEntity(params, HTTP.UT

36、F_8);/ 发送POST请求HttpResponse response = httpClient.execute(post);/ 如果服务器成功地返回响应if (response.getStatusLine().getStatusCode() = 200)String msg = EntityUtils.toString(response.getEntity();/ 提示登录成功Toast.makeText(HttpClientTest.this,msg, 5000).show();catch (Exception e)e.printStackTrace();).setNegativeBut

37、ton(取消, null).show(););3 使用 WebView浏览网页WebView就是一个浏览器实现,内核是 WebKit引擎常用方法:goBack()goForward()loadUrl(String Url)boolean zoomIn() 放大boolean zoomOut() 缩小3.1 使用 WebView浏览网页(P506, MiniBrowser)public class MiniBrowser extends ActivityEditText url;WebView show;Overridepublic void onCreate(Bundle savedInsta

38、nceState)super.onCreate(savedInstanceState);setContentView(R.layout.main);/ 获取页面中文本框、WebView组件url = (EditText) findViewById(R.id.url);show = (WebView) findViewById(R.id.show);Overridepublic boolean onKeyDown(int keyCode, KeyEvent event)if (keyCode = KeyEvent.KEYCODE_SEARCH)String urlStr = url.getTex

39、t().toString();/ 加载、并显示urlStr对应的网页show.loadUrl(urlStr);return true;return false;3.2 使用 WebView 加载html代码(P508, ViewHtml)WebView 提供loadData(String data,String mimeType,string encoding) 方法用于加载并显示HTML文档。但中文处理不好loadDataWithBaseUrl(String baseUrl,String data,String mineType,String encoding, String history

40、Uri) 支持中文data:代表html文档的字符串mineType : “text/html”Encoding: 字符集,可以为 “GBK”,”UTF-8”3.2 使用 WebView 加载html代码(P508, ViewHtml)public class ViewHtml extends ActivityWebView show;Overridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.main);/ 获取程序中的Web

41、View组件show = (WebView) findViewById(R.id.show);StringBuilder sb = new StringBuilder();/ 拼接一段HTML代码sb.append();sb.append();sb.append( 欢迎您 );sb.append();sb.append();sb.append( 欢迎您访问+ 疯狂Java联盟);sb.append();sb.append();/ 使用简单的loadData方法会导致乱码,可能是Android API的Bug/show.loadData(sb.toString() , “text/html” , “utf-8”); /”GBK”就乱码了/ 加载、并显示HTML代码show.loadDataWithBaseURL(nul

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论