面试篇--android下网络通讯机制(三种网络通讯方式)

HttpClient

HttpClient是Apache对java中的HttpURLClient接口的封装,主要引用org.apache.http.**。Google在2.3版本之前推荐使用HttpClient,因为这个封装包安全性高,bug较少。

使用方法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;



public class HttpClientUtils {
    private static HttpClient httpClient;
    private static HttpClientUtils instance = null;

    public static synchronized HttpClientUtils getInstance() {
        if (instance == null) {
            instance = new HttpClientUtils();
        }
        return instance;
    }

    private HttpClientUtils() {
        // 学习volley请求队列,HttpClient使用单例模式
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
        }
    }
    /**
     * 以get方式发送请求,访问接口
     * @param uri链接地址
     * @return 响应数据
     */
    private static String doHttpGet(String uri) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpGet request = new HttpGet(uri);
        try {
            // 发送请求,得到响应
            HttpResponse response = httpClient.execute(request);
            // 请求成功,statuscode返回200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb) {
            result = sb.toString();
        }
        return result;
    }

    /**
     * 以post方式发送请求,访问接口
     * @param uri链接地址
     * @return 响应数据
     */
    private static String doHttpPost(String uri) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpPost request = new HttpPost(uri);

        // 保存要传递的参数
        List params = new ArrayList();
        // 添加参数
        params.add(new BasicNameValuePair("parameter", "以Post方式发送请求"));

        try {
            // 设置字符集
            HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
            // 请求对象
            request.setEntity(entity);
            // 发送请求
            HttpResponse response = httpClient.execute(request);
            // 请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("post success");
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb) {
            result = sb.toString();
        }
        return result;
    }

}

HttpURLConnection

HttpURLConnection在java.NET下,继承自URLConnection类,相对于HttpClient具有扩展性高、灵活性高,更轻量级的优点,所以Google在2.3版本之后推荐大家使用HttpURLConnection来操作网络请求。

使用方法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class HttpURLConnectUtils {

    private static HttpURLConnectUtils instance = null;

    public static synchronized HttpURLConnectUtils getInstance() {
        if (instance == null) {
            instance = new HttpURLConnectUtils();
        }
        return instance;
    }

    private HttpURLConnectUtils() {
    }

    // post
    public String dohttppost(String mUrl) throws IOException {

        URL url = new URL(mUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//初始化创建HttpURLConnection实例
        httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
        httpURLConnection.setRequestMethod("POST");
        //设置参数
        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        String params = new String();//这里简单设置参数
        params = "name=" + URLEncoder.encode("高冉", "GBK");
        objectOutputStream.writeBytes(params);
        objectOutputStream.flush();
        objectOutputStream.close();
        //接收返回值
        //String msg = httpURLConnection.getResponseMessage();// 接收简单string
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
            builder.append(s);
        }
        return builder.toString();
    }

    // get
    public String dohttpget(String mUrl) throws IOException {
        URL url = new URL(mUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();

        // String msg = httpURLConnection.getResponseMessage();

        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
            builder.append(s);
        }

        return builder.toString();
    }
}

还需要注意一些细节:

1、post与get区别在于post将参数置于请求数据中,get则跟在url链接后面。
2、大文件下载操作要置于sd卡中,不要放在手机内存中操作,而且需要边读边写,不要使用Buffered做缓存。




三、我们看一个简单的socket编程,实现服务器回发客户端信息。

下面用个例子来说明:

A、客户端:

新建Android项目工程:SocketForAndroid(这个随意起名字了吧,我是以这个建立的!)

下面是main_activity.xml的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"1.0" encoding= "utf-8" ?>
"http://schemas.android.com/apk/res/android"
  android:layout_width= "fill_parent"
  android:layout_height= "fill_parent"
  android:orientation= "vertical" >
 
   android:layout_width= "fill_parent"
   android:layout_height= "wrap_content"
   android:text= "@string/hello" />
 
   android:id= "@+id/message"
   android:layout_width= "match_parent"
   android:layout_height= "wrap_content"
   android:hint= "@string/hint" />
 
   android:id= "@+id/send"
   android:layout_width= "fill_parent"
   android:layout_height= "wrap_content"
   android:text= "@string/send" />

MainActivity.java的代码入下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.yaowen.socketforandroid;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
  private EditText message;
  private Button send;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super .onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   //初始化两个UI控件
   message = (EditText) findViewById(R.id.message);
   send = (Button) findViewById(R.id.send);
   //设置发送按钮的点击事件响应
   send.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     Socket socket = null ;
     //获取message输入框里的输入的内容
     String msg = message.getText().toString() + "\r\n" ;
     try {
      //这里必须是192.168.3.200,不可以是localhost或者127.0.0.1
      socket = new Socket( "192.168.3.200" , 18888 );
      PrintWriter out = new PrintWriter(
        new BufferedWriter(
          new OutputStreamWriter(
            socket.getOutputStream()
          )
        ), true );
      //发送消息
      out.println(msg);
      //接收数据
      BufferedReader in = new BufferedReader(
       new InputStreamReader(
        socket.getInputStream()
       )
      );
      //读取接收的数据
      String msg_in = in.readLine();
      if ( null != msg_in) {
       message.setText(msg_in);
       System.out.println(msg_in);
      } else {
       message.setText( "接收的数据有误!" );
      }
      //关闭各种流
      out.close();
      in.close();
     } catch (IOException e) {
      e.printStackTrace();
     } finally {
      try {
       if ( null != socket) {
        //socket不为空时,最后记得要把socket关闭
        socket.close();
       }
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
   });
  }
}

最后别忘记添加访问网络权限:

B、服务端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package service;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerAndroid implements Runnable {
  @Override
  public void run() {
  Socket socket = null ;
  try {
  ServerSocket server = new ServerSocket( 18888 );
  // 循环监听客户端链接请求
  while ( true ) {
  System.out.println( "start..." );
  // 接收请求
  socket = server.accept();
  System.out.println( "accept..." );
  // 接收客户端消息
  BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
  String message = in.readLine();
  System.out.println(message);
  // 发送消息,向客户端
  PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),
   true );
  out.println( "Server:" + message);
  // 关闭流
  in.close();
  out.close();
  }
  } catch (IOException e) {
  e.printStackTrace();
  } finally {
  if ( null != socket) {
  try {
   socket.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
  }
  }
  // 启动服务器
  public static void main(String[] args) {
  Thread server = new Thread( new ServerAndroid());
  server.start();
  }
}

C、启动服务器,控制台会打印出“start...”字符串!

D、运行Android项目文件,如下图:



在输入框里输入如下字符串,点发送按钮:



服务器收到客户端发来的消息并打印到控制台:











你可能感兴趣的:(android)