Android's network programming is divided into 2 types: socket-based, and HTTP protocol-based.
Socket-based usage
Server-side:
First start a server-side socket serversocket SVR = new ServerSocket (8989);
Start listening for the request Socket s = svr.accept ();
Get input and output datainputstream dis = new DataInputStream (S.getinputstream ());
DataOutputStream dos = new DataOutputStream (S.getoutputstream ());
The interaction of the socket is done through a stream, that is, the transmitted byte stream, so any file can be transmitted on it. Whoever opens it, remember to close it.
Packaging with Datainputstream/dataoutputstream is because we want them to read and write to basic data types Readint (), Writeint (), readUTF (), writeUTF (), and so on.
Client:
Initiate a socket connection socket s = new socket ("192.168.1.200", 8989);
Get input and output datainputstream dis = new DataInputStream (S.getinputstream ());
DataOutputStream dos = new DataOutputStream (S.getoutputstream ());
Then they can communicate with each other. Whoever opens it, remember to close it.
Based on HTTP protocol
Typically, a request is sent to an application server. You need to use the httpurlconnection now.
First get httpurlconnection urlconn = new URL ("http://www.google.com"). OpenConnection ();
Set flag
Urlconn.setdooutput (TRUE); Urlconn.setdoinput (true);//post need to set Dooutput to True
Urlconn.setrequestmethod ("POST");
Urlconn.setusecache (false);//Set whether to use cache
Urlconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");//Set Content-type
Get the output stream, which makes it easy to send information to the server.
DataOutputStream dos = new DataOutputStream (Urlconn.getoutputstream ());
Read the request parameters in the flow
Dos.writebytes ("Name=" +urlencoder.encode ("Chenmouren", "gb2312");
Dos.flush ();d os.close ();//close immediately after sending.
Get input stream, fetch data
Bufferreader reader = new BufferedReader (New InputStreamReader (Urlconn.getinputstream ()));
Reader.readline ();//Use!=null to determine whether the end
Reader.close ();
After reading, remember to close connection urlconn.disconnect ();
The process record ends there.
Hara http://www.cnblogs.com/chenmouren/archive/2011/07/22/2114505.html