Android的网络编程分为2种:Socket网络通信和Http网络通信。
Http通信以xml或者json(JavaScript Object Notation)为载体,相互通信数据。json:一种简单的数据格式,比xml更轻巧。json 是JavaScript原生格式,这意味着在JavaScript中处理json数据不需要任何特殊的API或工具包。
Socket与Http不同的是两个的协议不同:Socket是面向TCP/UDP协议(位于传输层)的,Http是面向HTTP协议(位于应用层)的。
Android对于Http网络通信,提供了标准的Java接口--HttpURLConnection接口和Apache的接口--HttpClient接口。同时Http通信也分为Post方式和Get方式,两个相比较的话,post传送的数据量比较大,安全性也比较发高。
下面展示了Android SDK中的一些与网络有关的API包名:
包 描述
Java.net提供与联网有关的类,包括流和数据包(datagram)socket、internet协议和常见HTTP处理。该包是一个多功能网络资源
。。。。。。
Socket通信两种方式
1、基于TCP协议
android端实现:
- protected void connectServerWithTCPSocket() {
- Socket socket;
- try {// 创建一个Socket对象,并指定服务端的IP及端口号
- socket = new Socket("192.168.1.32", 1989);
- // 创建一个InputStream用户读取要发送的文件。
- InputStream inputStream = new FileInputStream("e://a.txt");
- // 获取Socket的OutputStream对象用于发送数据。
- OutputStream outputStream = socket.getOutputStream();
- // 创建一个byte类型的buffer字节数组,用于存放读取的本地文件
- byte buffer[] = new byte[4 * 1024];
- int temp = 0;
- // 循环读取文件
- while ((temp = inputStream.read(buffer)) != -1) {
- // 把数据写入到OuputStream对象中
- outputStream.write(buffer, 0, temp);
- }
- // 发送读取的数据到服务端
- outputStream.flush();
- /** 或创建一个报文,使用BufferedWriter写入,看你的需求 **/
- // String socketData = "[2143213;21343fjks;213]";
- // BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
- // socket.getOutputStream()));
- // writer.write(socketData.replace("\n", " ") + "\n");
- // writer.flush();
- /************************************************/
- } catch (UnknownHostException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
服务器端简单实现:
- public void ServerReceviedByTcp() {
- // 声明一个ServerSocket对象
- ServerSocket serverSocket = null;
- try {
- // 创建一个ServerSocket对象,并让这个Socket在1989端口监听
- serverSocket = new ServerSocket(1989);
- // 调用ServerSocket的accept()方法,接受客户端所发送的请求,
- // 如果客户端没有发送数据,那么该线程就停滞不继续
- Socket socket = serverSocket.accept();
- // 从Socket当中得到InputStream对象
- InputStream inputStream = socket.getInputStream();
- byte buffer[] = new byte[1024 * 4];
- int temp = 0;
- // 从InputStream当中读取客户端所发送的数据
- while ((temp = inputStream.read(buffer)) != -1) {
- System.out.println(new String(buffer, 0, temp));
- }
- serverSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
2、基于UDP协议
客户端发送数据实现:
- protected void connectServerWithUDPSocket() {
- DatagramSocket socket;
- try {
- //创建DatagramSocket对象并指定一个端口号,注意,如果客户端需要接收服务器的返回数据,
- //还需要使用这个端口号来receive,所以一定要记住
- socket = new DatagramSocket(1985);
- //使用InetAddress(Inet4Address).getByName把IP地址转换为网络地址
- InetAddress serverAddress = InetAddress.getByName("192.168.1.32");
- //Inet4Address serverAddress = (Inet4Address) Inet4Address.getByName("192.168.1.32");
- String str = "[2143213;21343fjks;213]";//设置要发送的报文
- byte data[] = str.getBytes();//把字符串str字符串转换为字节数组
- //创建一个DatagramPacket对象,用于发送数据。
- //参数一:要发送的数据 参数二:数据的长度 参数三:服务端的网络地址 参数四:服务器端端口号
- DatagramPacket packet = new DatagramPacket(data, data.length ,serverAddress ,10025);
- socket.send(packet);//把数据发送到服务端。
- } catch (SocketException e) {
- e.printStackTrace();
- } catch (UnknownHostException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
客户端接收服务器返回的数据:
- public void ReceiveServerSocketData() {
- DatagramSocket socket;
- try {
- //实例化的端口号要和发送时的socket一致,否则收不到data
- socket = new DatagramSocket(1985);
- byte data[] = new byte[4 * 1024];
- //参数一:要接受的data 参数二:data的长度
- DatagramPacket packet = new DatagramPacket(data, data.length);
- socket.receive(packet);
- //把接收到的data转换为String字符串
- String result = new String(packet.getData(), packet.getOffset(),
- packet.getLength());
- socket.close();//不使用了记得要关闭
- System.out.println("the number of reveived Socket is :" + flag
- + "udpData:" + result);
- } catch (SocketException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
服务器接收客户端实现:
- public void ServerReceviedByUdp(){
- //创建一个DatagramSocket对象,并指定监听端口。(UDP使用DatagramSocket)
- DatagramSocket socket;
- try {
- socket = new DatagramSocket(10025);
- //创建一个byte类型的数组,用于存放接收到得数据
- byte data[] = new byte[4*1024];
- //创建一个DatagramPacket对象,并指定DatagramPacket对象的大小
- DatagramPacket packet = new DatagramPacket(data,data.length);
- //读取接收到得数据
- socket.receive(packet);
- //把客户端发送的数据转换为字符串。
- //使用三个参数的String方法。参数一:数据包 参数二:起始位置 参数三:数据包长
- String result = new String(packet.getData(),packet.getOffset() ,packet.getLength());
- } catch (SocketException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
一、Java接口--HttpURLConnection
1、get方式
- //http地址
- String httpUrl = "http://192.168.1.110:8080/http1.jsp";
- //获得的数据
- String resultData = "";
- URL url = null;
- try
- {
- //构造一个URL对象
- url = new URL(httpUrl);
- }
- catch (MalformedURLException e)
- {
- Log.e(DEBUG_TAG, "MalformedURLException");
- }
- if (url != null)
- {
- try
- {
- //使用HttpURLConnection打开连接
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- //得到读取的内容(流)
- InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
- // 为输出创建BufferedReader
- BufferedReader buffer = new BufferedReader(in);
- String inputLine = null;
- //使用循环来读取获得的数据
- while (((inputLine = buffer.readLine()) != null))
- {
- //我们在每一行后面加上一个"\n"来换行
- resultData += inputLine + "\n";
- }
- //关闭InputStreamReader
- in.close();
- //关闭http连接
- urlConn.disconnect();
- //设置显示取得的内容
- if ( resultData != null )
- {
- mTextView.setText(resultData);
- }
- else
- {
- mTextView.setText("读取的内容为NULL");
- }
- }
- catch (IOException e)
- {
- Log.e(DEBUG_TAG, "IOException");
- }
- }
当访问有参数的jsp网页时,只需要在url的末端加上参数即可,这是因为HttpURLConnection默认的访问方式为GET,
url:http://192.168.1.110:8080/http1.jsp?par=values
当要以post方式访问时,需要设置进行setRequestMethod设置,如果无参数直接访问,有参数的话要通过writeBytes写入数据流。
示例:
- try
- {
- String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
- // 使用HttpURLConnection打开连接
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- //因为这个是post请求,设立需要设置为true
- urlConn.setDoOutput(true);
- urlConn.setDoInput(true);
- // 设置以POST方式
- urlConn.setRequestMethod("POST");
- // Post 请求不能使用缓存
- urlConn.setUseCaches(false);
- urlConn.setInstanceFollowRedirects(true);
- // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
- urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
- // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
- // 要注意的是connection.getOutputStream会隐含的进行connect。
- urlConn.connect();
- //DataOutputStream流
- DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
- //要上传的参数
- String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
- //将要上传的内容写入流中
- out.writeBytes(content);
- //刷新、关闭
- out.flush();
- out.close();
- //获取数据
- BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
- String inputLine = null;
- //使用循环来读取获得的数据
- while (((inputLine = reader.readLine()) != null))
- {
- //我们在每一行后面加上一个"\n"来换行
- resultData += inputLine + "\n";
- }
- reader.close();
- //关闭http连接
- urlConn.disconnect();
- //设置显示取得的内容
- if ( resultData != null )
- {
- mTextView.setText(resultData);
- }
- else
- {
- mTextView.setText("读取的内容为NULL");
- }
- }
- catch (IOException e)
- {
- Log.e(DEBUG_TAG, "IOException");
- }
如果是下载一幅图片并显示,则将下载的InputStream转化为BitMap即可
- InputStream is=conn.getInputStream();
- Bitmap bt=BitmapFactory.decodeStream(is);
- return bt;.
二、Apache接口--HttpClient
1、get方式
- String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
- //HttpGet连接对象
- HttpGet httpRequest = new HttpGet(httpUrl);
- try
- {
- //取得HttpClient对象
- HttpClient httpclient = new DefaultHttpClient();
- //请求HttpClient,取得HttpResponse
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- //请求成功
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
- {
- //取得返回的字符串
- String strResult = EntityUtils.toString(httpResponse.getEntity());
- mTextView.setText(strResult);
- }
- else
- {
- mTextView.setText("请求错误!");
- }
- }
- catch (ClientProtocolException e)
- {
- mTextView.setText(e.getMessage().toString());
- }
2、post方式
- String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
- //HttpPost连接对象
- HttpPost httpRequest = new HttpPost(httpUrl);
- //使用NameValuePair来保存要传递的Post参数
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //添加要传递的参数
- params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
- try
- {
- //设置字符集
- HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
- //请求httpRequest
- httpRequest.setEntity(httpentity);
- //取得默认的HttpClient
- HttpClient httpclient = new DefaultHttpClient();
- //取得HttpResponse
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- //HttpStatus.SC_OK表示连接成功
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
- {
- //取得返回的字符串
- String strResult = EntityUtils.toString(httpResponse.getEntity());
- mTextView.setText(strResult);
- }
- else
- {
- mTextView.setText("请求错误!");
- }
- }
- catch (ClientProtocolException e)
- {
- mTextView.setText(e.getMessage().toString());
- }
- }