Android 网络通信机制

简单地说有下面三种:

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

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

第二种 Apache接口---HttpClient

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

第三种 套接字 Socket网络接口

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

另外还有种: Android.net网络接口

android自带的接口,常常使用此包下的类进行Android特有的网络编程,如:访问WiFi,访问Android联网信息,邮件等功能。

private Context mContext;
 AndroidNet(Context context) {
    this.mContext = context;
}
/**
 *     确定您是否连入了互联网
 *     如果您未连入互联网,则无需安排基于互联网资源的更新。 下面这段代码展示了如何利用 ConnectivityManager 查询活动网络并确定其是否连入了互联网。
 * @return true 已连接
 */
private boolean IsNoConnected( ) {
    ConnectivityManager cm =
            (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    //是否是wifi
    //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
    return isConnected;
}
这个在https://developer.android.google.cn/reference/android/net/wifi/package-summary有讲。

这里详细介绍一下 HttpURLConnection接口---Google官方推荐

HttpURLConnection的压缩和缓存机制可以有效地减少网络访问的流量,提升速度和省电。

HttpURLConnection默认使用Get请求:

public void sendRequest(String url) throws IOException {
    String line = null;.
    String result = null;
    //使用HttpURLConnection 打开链接
    try{
        Url mUrl = new Url(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection ) mUrl.openConnection();
        //读取响应的内容(流)
        InputStreamReader mInputStreamReader = new InputStreamReader(new InputStream(mHttpURLConnection.getInputStream()));
        BufferedReader mBufferedReader = new BufferedReader(mInputStreamReader );
        if ((line = mBufferedReader.readLine())) {
            result = line + “\n”;
        }
        Log.e("", "请求结果:" + result);
     } catch ((MalformedURLException e)    
        {    
            Log.e(DEBUG_TAG, "MalformedURLException");    
        } finally {
        mInputStreamReader.close();
        mHttpURLConnection.disconnect();
     }

} 

HttpURLConnection的Post请求:

public void sendRequest(String url) throws IOException {
    String line = null;.
    String result = null;
      try{
        Url mUrl = new Url(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection ) mUrl.openConnection();
        //设置读取超时为10秒
        mHttpURLConnection.setReadTimeout(10000);
        //设置链接超时为15秒
        mHttpURLConnection.setConnectionTimeout(15000);
        //设置请求方式
        mHttpURLConnection.setRequestMethod("Post");
        //接收输入流
        mHttpURLConnection.setDoInput(true);
        //启动输出流,当需要传递参数时需要开启
        mHttpURLConnection.setDoOutput(true);
        //添加Header
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        //添加请求参数
        List paramsList = new ArrayList();
        paramsList .add(new BasicNameValuePair("username", "myname"));
        paramsList .add(new BasicNameValuePair("password", "mypwd"));
        //将参数写入到输出流
        wriParams(mHttpURLConnection.getOutputStream(), paramsList);
        
        //发起请求
        mHttpURLConnection.connect();
        BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mHttpURLConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        while((line = mBufferedReader.readLine()) != null) {
            sb.append(line + "\n");
        }
        result = sb.toString();
         } catch ((MalformedURLException e)    
        {    
            Log.e(DEBUG_TAG, "MalformedURLException");    
        } finally {
        mHttpURLConnection.disconnect();
     }

}

private void writeParams(OutputStream mOutputStream, List paramsList){
      StringBuilder paramStr = new StringBuilder();
      for (NameValuePair pair : paramsList) {
          if (!TextUtils.isEmpty(paramStr)) {
              paramStr.append("&"):
          }
          paramStr.append(URLEncoder.encode(pair.getName(), "UTF-8"));
          paramStr.append("=");
          paramStr.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
      }
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mOutputStream, "UTF-8"));
      //将参数写入输出流
      writer.write(paramStr.toString());
      writer.flush();
      writer.close();
}

注:任何输出流都是有缓冲区的,Bufferedxxx这种输出流提供可配置缓冲区大小,其他输出流都是有默认大小的缓冲区的,FileWriter的flush()方法是从OutputStreamWriter中继承来的,其作用就是 清空缓冲区并完成文件写入操作的。

你可能感兴趣的:(Android 网络通信机制)