• android 网络接口和HTTP通信


    Android平台有3种网络接口可以使用,它们分别是: java.net.*(标准Java接口)、org.apache(Apache接口)和android.net.*(Android网络接口)。

    1.标准java接口

    java.net.*提供与联网有关的类,包括流和数据包套接字、Internet协议、常见HTTP处理。下面是例子:

            try {
                //定义地址
                URL url = new URL("http://www.google.com");
                //打开连接
                HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
                //得到连接状态
                int nRC = http.getResponseCode();
                if(nRC == HttpsURLConnection.HTTP_OK){
                    //取得数据
                    InputStream is = http.getInputStream();
                    //处理数据
                    //...
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    2.Apache接口

      Apache HttpClient

            try {
                //创建HttpClient
                //这是使用DefaultHttpClient表示默认属性
                HttpClient hc = new DefaultHttpClient();
                //HttpGet实例
                HttpGet get = new HttpGet("http://www.google.com");
                HttpResponse rp = hc.execute(get);
                if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    InputStream is = rp.getEntity().getContent();
                    //处理数据
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    3.Android网络接口

      android.net.*包实际上是通过对apache中HttpClient的封装来实现的一个HTTP编程接口,同时还提供了HTTP请求队列管理以及HTTP连接池管理,以提高并发请求情况下和处理效率,除此之外还有网络状态监视等接口、网络访问的Socket、常用的Uri以及有关wifi相关的类

            try {
                InetAddress inetAddress = InetAddress.getByName("192.168.1.10");
                Socket client = new Socket(inetAddress, 6000, true);
                InputStream in = client.getInputStream();
                OutputStream out = client.getOutputStream();
                out.close();
                in.close();
                client.close();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (Exception e) {
                // TODO: handle exception
            }

    Http通信

      Android提供了HttpURLConnection和HttpClient接口来开发HTTP程序。

    1.HttpURLConnection接口

      get,  post.  get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给服务器。post和get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求数据是。

            URL url;
            try {
                //定义地址
                url = new URL("http://www.google.com");
                //打开连接
                HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
                //设置输入输出流
                http.setDoOutput(true);
                http.setDoInput(true);
                //设置方式为post
                http.setRequestMethod("POST");
                //post请求不能使用缓存
                http.setUseCaches(false);
                
                InputStreamReader in = new InputStreamReader(http.getInputStream());
                BufferedReader buffer = new BufferedReader(in);
                String inputline = null;
                String resultData = null;
                while((inputline = buffer.readLine()) != null){
                    resultData += inputline + "
    ";
                }
                //关闭连接
                http.disconnect();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }    

    2.HttpClient接口

      ClientConnectionManager接口

      DefaultHttpClient

      HttpResponse

      2.1  get方法

                    try {  
                        //得到HttpClient对象  
                        HttpClient getClient = new DefaultHttpClient();  
                        //得到HttpGet对象  
                        HttpGet request = new HttpGet("http://www.google.com");  
                        //客户端使用GET方式执行请教,获得服务器端的回应response  
                        HttpResponse response = getClient.execute(request);  
                        //判断请求是否成功    
                        if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
                            //获得输入流  
                            InputStream  inStrem = response.getEntity().getContent();  
                            int result = inStrem.read();  
                            while (result != -1){  
                                System.out.print((char)result);  
                                result = inStrem.read();  
                            }  
                            //关闭输入流  
                            inStrem.close();      
                        }else {  
    
                        }             
                    } catch (Exception e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  

     使用HTTP GET调用有一个缺点就是,请求的参数作为URL一部分来传递,以这种方式传递的时候,URL的长度应该在2048个字符之内。如果超出这个这范围,就要使用到HTTP POST调用。

     2.2  POST 方法

      使用POST调用进行参数传递时,需要使用NameValuePair来保存要传递的参数。NameValuePair封装了一个键/值组合。另外,还需要设置所使用的字符集。

            BufferedReader in = null;  
            try {  
                HttpClient client = new DefaultHttpClient();  
                HttpPost request = new HttpPost("http://code.google.com/android/");  
                //使用NameValuePair来保存要传递的Post参数  
                List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
                //添加要传递的参数    
                postParameters.add(new BasicNameValuePair("id", "12345"));  
                postParameters.add(new BasicNameValuePair("username", "dave"));  
                //实例化UrlEncodedFormEntity对象  
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
                        postParameters);  
     
                //使用HttpPost对象来设置UrlEncodedFormEntity的Entity  
                request.setEntity(formEntity);  
                HttpResponse response = client.execute(request);  
                in = new BufferedReader(  
                        new InputStreamReader(  
                                response.getEntity().getContent()));  
     
                StringBuffer string = new StringBuffer("");  
                String lineStr = "";  
                while ((lineStr = in.readLine()) != null) {  
                    string.append(lineStr + "
    ");  
                }  
                in.close();  
     
                String resultStr = string.toString();  
                System.out.println(resultStr);  
            } catch(Exception e) {  
                // Do something about exceptions  
            } finally {  
                if (in != null) {  
                    try {  
                        in.close();  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
  • 相关阅读:
    Mysql 存储引擎中InnoDB与Myisam的主要区别
    [转]memmove函数
    _Obj* __STL_VOLATILE* __my_free_list
    [转]STL的内存分配器
    [转载]C++ 堆与栈简单的介绍
    [转载]__type_traits
    [转载]C++中 引用&与取地址&的区别
    [转载]delete指针之后应该赋值NULL
    [转载]C++中声明与定义的区别
    学习笔记ubuntu/shell
  • 原文地址:https://www.cnblogs.com/bing11/p/3707179.html
Copyright © 2020-2023  润新知