Android 网络编程(一)Http网络请求详解?

来源:互联网 发布:优化游戏速度插件安裝 编辑:程序博客网 时间:2024/06/02 04:19

Http 介绍

Http 是一种应用层协议,注意是应用层,也就是最上层了。它通过TCP 实现了可靠的数据传输。
详细步骤: 访问www.baidu.com

  • 客户端从URL 中解析出服务器的主机名,端口号,将主机名转换为服务器的IP地址。
  • 根据ip 地址和端口建立一条和服务器的TCP连接。
  • 客户端通过输入流向服务器发送一跳HTTP请求。
  • 服务器端给客户端回复一条HTTP 响应报文,当然是以流的形式了。
  • 客户端从输入流获取报文。解析报文。
  • 拿到响应了,想干嘛干嘛。关闭连接。

参考博客

  • 在浏览器中输入网址到网页显示的过程分析
  • Http详解

Http分析神器 fiddler

可以查看电脑或者手机请求网络的请求报文和响应报文。
传送门

请求报文

接上,访问www.baidu.com 请求报文为:

GET / HTTP/1.1Host: www.baidu.comConnection: keep-aliveAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36Accept-Encoding: gzip, deflate, sdchAccept-Language: zh-CN,zh;q=0.8Cookie: BDUSS=ENqeU4wanp3U2FvQjJqM2wxcTRMUURDZm5rMEpha

这些请求,比如:

  • Connection:
  • Accept:
  • Accept-Encoding:
    这些都是浏览器帮我们设置的,在android 客户端里,有些是需要我们自己设置的。

响应报文

HTTP/1.1 200 OKContent-Length: 17012Date: Sun, 24 Apr 2016 21:17:57 GMTServer: BWS/1.1Content-Type: text/html; charset=utf-8Connection: Keep-Alive<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta name="referrer" content="never"><title>百度一下,你就知道tps://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/home/img/sugbg_6a9201c2.png) 100% 100% no-repeat #fff;background-size:100px class="lb">登录</a><a href="http://www.baidu.com/gaoji/preferences.html" name="tj_settingicon" class="pf">设置</a><a href="http://www.baidu.com/more/" name="tj_briicon" class="bri" >更多产品</a></div></div></div> <div id="ftCon"> <div id="ftConw"> <p id="lh"> <a id="setf" href="http://www.baidu.com/cache/sethelp/index.html" target="_blank">把百度设为主页</a><a href="http://home.baidu.com">关于百度</a><a href="http://ir.baidu.com">About Baidu</a></p><p id="cp">&copy;2015&nbsp;Baidu&nbsp;<a href="http://www.baidu.com/duty/" name="tj_duty">使用百度前必读</a>.......省略.................

Android 中执行网络请求

这里以Httpclient 为例:

        //设置按钮点击事件,向百度百科发送一个get请求        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {            new Thread(new Runnable() {                @Override                public void run() {                    try {                        sendGetRequest("http://baike.baidu.com/link?url=hzde4p2h38uP6S6jDKsv9E1UiUqI7SGEEB0tIpxqnzxF5GtRZsksIq8W5dBCENOoS1JrNGqWle8r2nHfGmERwK");                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }).start();            }        });    }    public void sendGetRequest(String url) throws Exception{        //c创建一个HttpClient对象,传入Http 参数        HttpClient httpClient=new DefaultHttpClient(new BasicHttpParams());        //创建get请求 对象        HttpGet httpGet= new HttpGet(url);        // 添加响应头        httpGet.addHeader("Connection","Keep-Alive");        //执行 Http 请求,返回 HttpResponse 对象。        HttpResponse httpResponse=httpClient.execute(httpGet);        //得到HttpEntity        HttpEntity entity= httpResponse.getEntity();        if(entity!=null){            //得到返回的输入流            InputStream inputStream=entity.getContent();            //将输入流转换为String            String result=converStreamToString(inputStream);            Log.e("mytest",result);        }    }    /**     * 将Http 返回流转化为字符串     * @param is     * @return     * @throws Exception     */    public  static  String converStreamToString(InputStream is)throws Exception{        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));        StringBuilder stringBuilder=new StringBuilder();        String line;        while((line=bufferedReader.readLine())!=null){            stringBuilder.append(line+"\n");        }        return stringBuilder.toString();    }

返回结果如下:

<!DOCTYPE html>                                                                              <!--STATUS OK-->                                                                              <html>                                                                              <head>                                                                              <meta charset="UTF-8">                                                                              <meta http-equiv="X-UA-Compatible" content="IE=Edge" />                                                                              <meta name="description" content="Entity — 实体 ADO .NET Entity Framework 应用程序域中的一个概念,数据类型在该域中定义。 在计算机网络中,实体这一较为抽象的名词表示任何可能发送或接受信息的硬件或软件进程。在许多情况下,实体就是一个特定的软件模块。 ...">                                                                              <title>Entity_百度百科</title>                                                                              <meta name="keywords" content="Entity">                                                                              <meta name="image" content="http://baike.bdimg.com/cms/static/baike.png">                                                                              <script type="text/javascript">                                                                                void function(g,f,j,c,h,d,b){g.alogObjectName=h,g[h]=g[h]||function(){(g[h].q=g[h].q||[]).push(arguments)},g[h].l=g[h].l||+new Date,d=f.createElement(j),d.async=!0,d.src=c,b=f.getElementsByTagName(j)[0],b.parentNode.insertBefore(d,b)}(window,document,"script","http://img.baidu.com/hunter/alog/alog.min.js","alog");void function(){function c(){return;}window.PDC={mark:function(a,b){alog("speed.set",a,b||+new Date);alog.fire&&alog.fire("mark")},init:function(a){alog("speed.set","options",a)},view_start:c,tti:c,page_ready:c}}();void function(n){var o=!1;n.onerror=function(n,e,t,c){var i=!0;return!e&&/^script error/i.test(n)&&(o?i=!1:o=!0),i&&alog("exception.send","exception",{msg:n,js:e,ln:t,col:c}),!1},alog("exception.on","catch",function(n){alog("exception.send","exception",{msg:n.msg,js:n.path,ln:n.ln,method:n.method,flag:"catch"})})}(window);                                                                              </script>                                                                              <meta name="csrf-token" content="">                                                                              <!--[if lte IE 9]>                                                                              <script>                                                                                  (function() {                                                                                    var e = "abbr,article,aside,audio,canvas,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video".split(","),                                                                                      i = e.length;                                                                                    while (i--) {                                                                                      document.createElement(e[i]);                                                                                    }                                                                                  })();                                                                                </script>                                                                              <![endif]-->                                                                              <link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/pkg/wiki-lemma_9f91e0d.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-common/pkg/wiki-common-base_316fdfd.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/label/label_461cbe0.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/newSideShare/sideShare_3e4292c.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/praise/praise_2120cd2.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/searchHeader/toolButtons/toolButtons_a2c470f.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/searchHeader/toolButtons/userInfo_9ba20c1.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/video/pageMask/pageMask_ff9a193.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/pkg/wiki-lemma-module_65358f6.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/lemma_content/mainContent/mainContent_637f952.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/lemma_content/mainContent/lemmaRelation/lemmaRelation_9f629f5.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/lemma_content/configModule/zhixin/zhixin_1c34583.css"/><link rel="stylesheet" type="text/css" href="http://baike.bdimg.com/static/wiki-lemma/widget/tools/searchHeader/searchHeader_e786bfb.css"/></head>                                                                              <script type="text/javascript">                                                                                  alog('speed.set', 'ht', +new Date);                                                                              </script>                                                                              <body class="wiki-lemma normal">                                                                              <div class="header-wrapper">                                                                              <ul class="wgt-userbar">                                                                              <li>                                                                              <a href="http://www.baidu.com/">百度首页</a>                                                                              </li>                                                                              </ul>                                                                              <div class="header">                                                                              <div class="layout">                                                                              <div class="wgt-searchbar wgt-searchbar-main cmn-clearfix">                                                                              <div class="logo-container">                                                                              <a class="l

后话

在6.0上google 已经把HttpClient 从SDK中移除了。也就是不建议大家使用它了。
后续会学习推荐的网络访问方式 HttpUrlConnection 以及各种网络请求框架。

0 0
原创粉丝点击