Android 网络通信机制

    

       简单地说有下面三种:

第一种: java.net.* (标准java接口)

  try{
    URL url = new URL("http://www.google.com%22)//定义地址
    HttpURLConnection http = (HttpURLConnection) url.openConnection();//打开连接
    int nRC = http.getResponseCode();//得到连接状态
    if(nRC == HttpURLConnection.HTTP_OK){
     InputStream is = http.getInputStream();//取得数据
     .....//处理数据
    }
   }catch(Exception e){
    //因是连接网络,不免会出现一些异常,所以必须处理这些异常
   }

第二种 Apache接口

 try{
    HttpClient hc = new DefaultHttpClient();//创建HttpClient,这里使用DefaultHttpClient表示默认属性
    HttpGet hg = new HttpGet("http://www.google.com%22);//HttpGet实例
    HttpResponse rp = hc.execute(hg);//连接
    if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
     InputStream is = rp.getEntity().getContent();
     .....//处理数据
    }
   }catch(IOEeception e){
   }

第三中 Android网络接口

  try{
    InetAddress ia = InetAddress.getByName("192.168.1.110");//IP地址
    Socket sk = new Socket(inetAddress,61203,true);//端口
    InputStream is =sk.getInputStream();//得到数据
    OutputStream os = sk.getOutputStream();
    .....//数据处理
    os.close();
    is.close();
    sk.close();
   }catch(UnknownHostException e){
   }catch(IOException e){
   }

猜你喜欢

转载自blog.csdn.net/shenggaofei/article/details/52462470
今日推荐