android之http

来源:互联网 发布:电池校准软件 编辑:程序博客网 时间:2024/06/06 03:45

http是一个客户端和服务器端请求和应答得标准,是客户端的应用程序于Web服务器之间的应用层协议。

(感觉传输层应该是Socket编程吧,网络层应该是IP地址方面的知识吧,大概意思是不是首先获得IP地址,然后采用socket编程来传输数据,这个传输的方式要采用http协议?是时候回去看看计算机网络了!)

http请求方式有7种?我记得是。貌似现在流行的只有两种,get和post,我也就学了这两种。区别的话有一些:

1.get是从服务器上获取数据,post是向服务器发送数据

2.get发送的k-v消息会作为url的一部分被传送,而post则是将发送的k-v消息放在http请求消息内部(HTML HEADER)传送出去。

3.对于get方式,服务器端用Request.QueryString获取变量的值。对于post方式,服务器端用Request.Form获取提交的值。

4.get提交的数据最多能有1024字节,但post没有限制。

5.安全性上,使用get时,参数会显示在地址栏上,而post不会。

说http之前先讲一个知识点,URL(Uniform Resource Locator)统一资源定位符。

例如http://www.baidu.com/s/index.htm。这是一个完整的URL。

http://。代表超文本传输协议。底层协议是TCP/IP。

www。代表一个万维网服务器。这个不多说。

baidu.com。代表服务器的域名。IP地址也是将此放入DNS解析获取的。

s。子目录,类似我们的文件夹。放资源的地方。

index.htm。文件夹中的一个文件。一般这就是我们要访问的资源

/s/index.htm。统称为URL路径,也就是URI。

http编程有两种方式:

1.HttpClient(Apache)

刚开始敲代码导包的时候一直导不进来,才知道我这里没有apache的http.client的api。查了之后发现要导入6.0版本里的optional里的jar。用的时候居然过时了!才知道apache的http包好像在5.1版本中被废弃了,有了代替的新方法HttpURLConnection。既然都学了,那就在这里总结下吧。

public class MainActivity extends AppCompatActivity {    Button button1, button2;    //TextView textView1;    HttpResponse httpResponse = null;    HttpEntity httpEntity;    //url由三部分组成,协议http,域名www.baidu.com,资源s    String baseUrl = "http://www.baidu.com/s";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button1 = (Button) findViewById(R.id.button1);        button2 = (Button) findViewById(R.id.button2);        //textView1 = (TextView) findViewById(R.id.textview1);        //http操作get发送请求        button1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //4.0版本后network必须在子线程中,否则会报错                new Thread(new Runnable() {                    @Override                    public void run() {                        httpGet();                    }                }).start();            }        });        //http操作post发送请求        button2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //4.0版本后network必须在子线程中,否则会报错                new Thread(new Runnable() {                    @Override                    public void run() {                        httpPost();                    }                }).start();            }        });    }    //get发送请求    void httpGet() {        /**         * get发送请求是采用键值队的格式,具体格式是?开头,然后是Key=value,         * 如果请求里不止一个数据,就以&为分隔符         * 教学视频里讲的发送的请求后台都是用j2ee编写的,由于还不会,所以我找了个其他的方法         * 我在百度搜索栏输入1后,发现蹦出了资源s,还有后面的一串字符,跟get里讲的格式一样,         * 于是这里就是模拟在百度引擎输入1后的响应         */        String url = baseUrl + "?wd=1&rsv_spt=1&rsv_iqid=0xde5faba500046bbb&issp=1&f=3&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=sitehao123&rsv_enter=0&rsv_sug3=2&rsv_sug1=1&prefixsug=1&rsp=1&inputT=2715&rsv_sug4=2995";        //生成一个请求对象        HttpGet httpGet = new HttpGet(url);        //生成一个http客户端对象        HttpClient httpClient = new DefaultHttpClient();        InputStream inputStream = null;        BufferedReader bufferedReader = null;        try {            //使用http客户端发送请求对象,并返回http服务器端响应            httpResponse = httpClient.execute(httpGet);            //响应的内容,也就是数据            httpEntity = httpResponse.getEntity();            //获取输入流,来输出数据            inputStream = httpEntity.getContent();            //还能这么套?第一次见InputStreamReader            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));            //放置读取到的响应数据            String result = "";            String line;            //这里我试了下equals(""),最后会报空指针。            while ((line = bufferedReader.readLine()) != null) {                result = result + line;            }            //发现打印出来的和网页源代码一毛一样            System.out.println("==============" + result);        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (inputStream != null)                    inputStream.close();                if (bufferedReader != null)                    bufferedReader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    //post发送请求    void httpPost() {        /**         * post发送请求也是采用键值队的格式,不过不一样的是,采用的形式有点像Map,         * 就是把key和value放到一个容器里面,然后把这个容器发送出去,         * 这里还是模拟在百度引擎输入1后的响应         */        //这里把get里面的请求内容拆分成键值队然后放到NameValuePair这个对象里,好多啊!        NameValuePair nameValuePair1 = new BasicNameValuePair("wd", "1");        NameValuePair nameValuePair2 = new BasicNameValuePair("rsv_spt", "1");        NameValuePair nameValuePair3 = new BasicNameValuePair("rsv_iqid", "0xde5faba500046bbb");        NameValuePair nameValuePair4 = new BasicNameValuePair("issp", "1");        NameValuePair nameValuePair5 = new BasicNameValuePair("f", "3");        NameValuePair nameValuePair6 = new BasicNameValuePair("rsv_bp", "0");        NameValuePair nameValuePair7 = new BasicNameValuePair("rsv_idx", "2");        NameValuePair nameValuePair8 = new BasicNameValuePair("ie", "utf - 8");        NameValuePair nameValuePair9 = new BasicNameValuePair("tn", "sitehao123");        NameValuePair nameValuePair10 = new BasicNameValuePair("rsv_enter", "0");        NameValuePair nameValuePair11 = new BasicNameValuePair("rsv_sug3", "2");        NameValuePair nameValuePair12 = new BasicNameValuePair("rsv_sug1", "1");        NameValuePair nameValuePair13 = new BasicNameValuePair("prefixsug", "1");        NameValuePair nameValuePair14 = new BasicNameValuePair("rsp", "1");        NameValuePair nameValuePair15 = new BasicNameValuePair("inputT", "2715");        NameValuePair nameValuePair16 = new BasicNameValuePair("rsv_sug4", "2995");        //然后是放入list集合当中        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        nameValuePairs.add(nameValuePair1);        nameValuePairs.add(nameValuePair2);        nameValuePairs.add(nameValuePair3);        nameValuePairs.add(nameValuePair4);        nameValuePairs.add(nameValuePair5);        nameValuePairs.add(nameValuePair6);        nameValuePairs.add(nameValuePair7);        nameValuePairs.add(nameValuePair8);        nameValuePairs.add(nameValuePair9);        nameValuePairs.add(nameValuePair10);        nameValuePairs.add(nameValuePair11);        nameValuePairs.add(nameValuePair12);        nameValuePairs.add(nameValuePair13);        nameValuePairs.add(nameValuePair14);        nameValuePairs.add(nameValuePair15);        nameValuePairs.add(nameValuePair16);        //两个流,不多说        InputStream inputStream = null;        BufferedReader bufferedReader = null;        try {            //HttpEntity既可以表示响应的内容,也可以表示发送的内容,这里是发送            HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs);            //创建HttpPost请求对象,注意构造参数的url            HttpPost httpPost = new HttpPost(baseUrl);            //httpPost设置发送的内容            httpPost.setEntity(httpEntity);            //生成一个http客户端对象            HttpClient httpClient = new DefaultHttpClient();            //使用http客户端发送请求对象,并返回http服务器端响应            httpResponse = httpClient.execute(httpPost);            //响应的内容,也就是数据            httpEntity = httpResponse.getEntity();            //获取输入流,来输出数据            inputStream = httpEntity.getContent();            //还能这么套?第一次见InputStreamReader            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));            //放置读取到的响应数据            String result = "";            String line;            //这里我试了下equals(""),最后会报空指针。            while ((line = bufferedReader.readLine()) != null) {                result = result + line;            }            //这里返回的结果为什么是网页不存在?键值队拆错了?            System.out.println("==============" + result);        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (inputStream != null)                    inputStream.close();                if (bufferedReader != null)                    bufferedReader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

2.HttpURLConnection(Java)

现在ahache的http包被google弃用了,所以我们以后最好还是使用Java里的http来编程。

<span style="font-size:14px;">public class MainActivity extends AppCompatActivity {    Button button1, button2;    //url由三部分组成,协议http,域名www.baidu.com,资源s    static String BASE_URL = "http://www.baidu.com/s";    static String REQUEST_MESSAGE = "?wd=1&rsv_spt=1&rsv_iqid=0xde5faba500046bbb&issp=1&f=3&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=sitehao123&rsv_enter=0&rsv_sug3=2&rsv_sug1=1&prefixsug=1&rsp=1&inputT=2715&rsv_sug4=2995";    static String POST_MESSAGE = "?&ver=R2-vGAAFPODaje7apKKIyu9X10N5WCyNCoW&ie=utf-8&rsv_t=2cccv7nrgaXHRIlvvWd65WShSOFXcKFfLljv7Oa/ym9TE9oN2SQ4wpXiJYOH2opOhQ&rsv_stat=-2&rsv_pq=eec5cb7e000194cc&pstg=20&oq=1&mod=2&istc=424&isid=eec5cb7e000194cc&isbd=1&bs=1&f4s=1&csq=1&cqid=a7043267000170d6&chk=56263700&_ck=946.1.159.39.21.700.32wd=1&rsv_spt=1&f=3&rsv_bp=1&rsv_idx=2&tn=sitehao123&rsv_enter=0&rsv_sug3=2&rsv_sug1=1&prefixsug=1&rsp=0&inputT=2715&rsv_sug4=3938";    static String GET_URL = BASE_URL + "?wd=1&rsv_spt=1&rsv_iqid=0xde5faba500046bbb&issp=1&f=3&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=sitehao123&rsv_enter=0&rsv_sug3=2&rsv_sug1=1&prefixsug=1&rsp=1&inputT=2715&rsv_sug4=2995";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button1 = (Button) findViewById(R.id.button1);        button2 = (Button) findViewById(R.id.button2);        //http操作get发送请求        button1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //4.0版本后network必须在子线程中,否则会报错                new Thread(new Runnable() {                    @Override                    public void run() {                        httpGet();                    }                }).start();            }        });        //http操作post发送请求        button2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //4.0版本后network必须在子线程中,否则会报错                new Thread(new Runnable() {                    @Override                    public void run() {                        httpPost();                    }                }).start();            }        });    }    /**     * get发送请求。     * 这里没有输出流,是不是就是要发送的消息直接就在URL里面,当连接到服务器的时候,     * 服务器从URL里面就能读取到消息体的内容,而不需要单独从流里面读取。     * 而只需要打开一个输入流来读取服务器响应的消息     */    void httpGet() {        InputStream inputStream = null;        BufferedReader bufferedReader = null;        try {            //注意这个URL里面包含了请求的消息内容            URL url = new URL(GET_URL);            //获取http连接对象            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            //设置连接网络超时时间            httpURLConnection.setConnectTimeout(3000);            //打开输入流            httpURLConnection.setDoInput(true);            //这些是范围GET POST HEAD OPTIONS PUT DELETE TRACE            httpURLConnection.setRequestMethod("GET");            //获取连接的状态码,一般用来判断连接的状况            int responseCode = httpURLConnection.getResponseCode();            if (responseCode == 200) {//表示连接成功,对应的字段是HTTP_OK                //获取输入流,用来读出数据                inputStream = httpURLConnection.getInputStream();            }            if (inputStream != null)                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));            //读取出流中的数据            String result = "";            String line;            if (bufferedReader != null)                while ((line = bufferedReader.readLine()) != null) {                    result = result + line;                    System.out.println("------------" + line);                }            //发现打印出来的和网页源代码一毛一样            System.out.println("==============" + result);        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (inputStream != null)                    inputStream.close();                if (bufferedReader != null)                    bufferedReader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    /**     * post发送请求。     * 作为post发送的方式,请求的消息体不能写在URL里面,所以需要单独打开一个输入流来发送消息体。     * 当然也需要打开一个输入流来读取服务器响应的消息。     */    void httpPost() {        InputStream inputStream = null;        BufferedReader bufferedReader = null;        try {            //这只是个普通的额URL,里面没有的消息体            URL url = new URL(BASE_URL);            //获取http连接对象            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            //设置连接网络超时时间            httpURLConnection.setConnectTimeout(3000);            //表示从服务器获取数据            httpURLConnection.setDoInput(true);            //表示向服务器些数据            httpURLConnection.setDoOutput(true);            //这些是范围GET POST HEAD OPTIONS PUT DELETE TRACE            httpURLConnection.setRequestMethod("POST");            //获得上传信息的大小及字节            byte[] bytes = REQUEST_MESSAGE.getBytes();            //设置请求属性?这里我也不知道百度的请求属性怎么怎么设.这里是设置请求体的类型是文本类型            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");            //设置请求体的长度            httpURLConnection.setRequestProperty("Content-Type", String.valueOf(bytes.length));            //获得输出流,向服务器输出数据            OutputStream outputStream = httpURLConnection.getOutputStream();            //把请求信息写入到输出流当中,这里要不要用utf-8?            outputStream.write(bytes);            //获得服务器响应的结果和状态码            int requestCode = httpURLConnection.getResponseCode();            if (requestCode == 200) {                inputStream = httpURLConnection.getInputStream();            }            if (inputStream != null)                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));            //读取出流中的数据            String result = "";            String line;            if (bufferedReader != null)                while ((line = bufferedReader.readLine()) != null) {                    result = result + line;                    System.out.println("------------" + line);                }            //发现打印出来的和网页源代码没半毛钱关系!为什么收到的是百度发来的你访问的页面不存在?感觉应该是写入的格式错误了            System.out.println("==============" + result);        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (inputStream != null)                    inputStream.close();                if (bufferedReader != null)                    bufferedReader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}</span><span style="font-size: 18px;"></span>

这里为什么每次用post读取的数据没问题,但是发送的数据有问题,感觉应该是发送格式的问题,要么就是欠缺J2EE的知识点,不知道服务器的内部代码是怎么实现的。导致发送的消息格式不知道着怎么写。要学的知识还很多啊,这点疑问,先放这里,以后掌握了回来看看。



0 0