Android 网络编程

来源:互联网 发布:国内三大耳机论坛 知乎 编辑:程序博客网 时间:2024/06/07 00:37

一,Tcp

Server端

ServerSocket serverSocket = new ServerSocket(9999);//这时候堵塞在accept,知道客户端发出连接请求Socket clientSocket = serverSocket.accept();//网路上传送的数据流,所以得到streamInputStream inStream  = clientSocket.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(inStream));//readLine()也堵塞住,直到有数据可以读出String message = br.readLine();

client端

//执行下行代码,请求连接服务器。Socket clientSocket = new Socket("127.0.0.1",9999);//得到输出流,发送数据PrintWriter output = new PrintWriter(new BufferedWriter(                  new OutputStreamWriter(clientSocket.getOutputStream())),true);output.println("csdn");
二,Udp

Server端

//msg用于存放数据private byte[] msg = new byte[1024];DatagramPacket dPacket = new DatagramPacket(msg, msg.length);//没有连接过程,世界接收信息,放入dacket中,即msg中DatagramSocket udpSocket = new DatagramSocket(9999);udpSocket.receive(dPacket);String str = new String(dPacket.getData());
client端

String msg ="csdn";DatagramSocket dSocket = new DatagramSocket(); InetAddress local = InetAddress.getByName("localhost");DatagramPacket dPacket = new DatagramPacket(msg.getBytes(),msg.length(),local, 9999);dSocket.send(dPacket);
三,Http

Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。无需像C#那样关心通信协议,直接使用给定的步骤,按部就班就可一了。


1. HttpURLConnection接口

   首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。
    HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。创建方法如下代码所示:

URL url=new URL("https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=csdn");HttpURLConnection urlConn=(HttpURLConnection)url.openConnection(); //设置输入和输出流  urlConn.setDoInput(true);  urlConn.connect();//得到读取的内容(流)  InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  // 为输出创建BufferedReader  BufferedReader buffer = new BufferedReader(in);  //使用循环来读取获得的数据  String inputLine = null;while (((inputLine = buffer.readLine()) != null))  {      resultData.append(inputLine);}           //关闭InputStreamReader  in.close();  //关闭http连接  urlConn.disconnect(); 
2.HttpClient接口

GET方法

// http地址  String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";  //HttpGet连接对象  HttpGet httpRequest = new HttpGet(httpUrl);   //取得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("请求错误!");      }  

POST方法
//http地址  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"));  //设置字符集  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("请求错误!");  }