Web programming for Android Development notes-network programming using TCP protocols and URLs

Source: Internet
Author: User

The mobile phone itself is used as a mobile phone terminal, so its computing power, storage capacity is limited. Its main advantage is easy to carry, can be opened at any time, and the phone is always in the connected state. Therefore, network support is very important for mobile applications.

Android完全支持JDK本身的TCP,UDP网络通信API,也可以使用ServerSocket,Socket来建立基于TCP/IP协议的网络通信,也可以使用DatagramSocket,Datagrampacket来建立基于UDP协议的网络通信。Android也支持JDK提供的URL,URLConnection等网络通信API。Android还内置了HttpClient,和HttpUrlConnection这样可以非常方便地发送HTTP请求,并获取Http响应。

--Programming based on TCP protocol

    使用Socket,ServerSocket编程:    使用多线程,handler机制完成网络编程.    注意:由于手机无线上网的IP地址通常都是由移动运营公司动态分配的,一般不会有自己固定的IP地址,因此很少在手机上运行服务器端,服务器端通常运行在有固定IP的服务器上。    ①跟网络有关的就要加Internet权限    ②网络数据的请求要在子线程中进行    ③更新UI需要借助Handler机制    ④编码问题:Android默认编码为UTF-8   Java默认编码为GB2312    ⑤本机IP地址问题:使用127.0.0.1在模拟中不能访问到本地的服务器,因为模拟器也在本机

Finally there are examples of programming using Socket,serversocket Network

--Using URLs for network programming

   **——使用URL访问网络资源**   URL对象代表统一资源定位符。它是指向互联网中的资源。该资源可以是简单的文件或目录。也可以是对更复杂的对象的引用。   URL的格式:protocol://host:port/resourceName   可以使用构造器创建URL对象,一旦获得URL对象,可以调用如下的方法访问该URL对应的资源:  String getFile():获取URL的资源名  String getHost():获取URL的主机名  String getPath():获取URL的路径部分  int getPort():获取URL的端口号  String getProtocol():获取URL的协议名称  String getQuery():获取URL的查询字符串部分  InputStream url.openStream():打开URL的连接,返回一个读取该资源的InputStream。   **——使用URLConnection提交请求**   

The following steps are required:

A) Create a URLConnection object by calling the URL object OpenConnection () method

b) Set urlconnection parameters and normal request properties

conn.setRequestProperty("accept","*/*");conn.setRequestProperty("connection","Keep-Alive");conn.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

The following two lines must be set for sending a POST request * *

Conn.setdoinput (TRUE): Sets the value of the Doinput Request header field for this URLConnection

Coon.setdooutput (True):

c) call Connect (): Opens a communication link to the resource referenced by this URL if such a connection has not been established.

If the Connect method is called when the connection is open (the value of the connected field is true), the call is ignored.

The URLConnection object goes through two stages: creating the object first, and then establishing the connection.

After you create the object, you can specify various options (such as Doinput and usecaches) before you establish the connection. The error occurs when you connect and then set. Actions that can be made after the connection (for example, getcontentlength) and, if necessary, the connection is implicitly performed .

D) If you just send a Get method request, use the Connect method to establish an actual connection between the remote resource and the data in the requested address.

If you need to send a POST method request. Need to get
The URLConnection instance corresponding to the output stream to send the request parameters,

 PrintWriter out=new PrintWriter(conn.getOutputStream()); //解决乱码问题 String n=EncodingUtils.getString("张三".getBytes(),"UTF-8"); out.write("name="+n+"&pwd="+pwd); out.flush();//刷新输出流的缓冲

e) The remote resource becomes available, and the program can access the remote resource's header field or read the remote resource's data through the input stream.

getInputStream () gets the input stream.
Reads the response data from the input stream.

Attention:

1) If you want to use the input stream to read the contents of the URLConnection response, and also use the output stream to send request parameters, be sure to use the output stream before using the input stream.

2) with the help of the URLConnection class, the application can easily exchange information with the specified site, including sending get requests, post requests, and obtaining responses from the Web site.

Using the Socket,serversocket Programming Example:

Effect:

Serverhuadong for server
Network programming based on TCPIP protocol as client

: http://download.csdn.net

Web programming for Android Development notes-network programming using TCP protocols and URLs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.