Android Network Programming is divided into two types: socket-based and http-based.
Socket-based usage
Server:
Start a server socket ServerSocket svr = new ServerSocket (8989 );
Start listening for request Socket s = svr. accept ();
Obtain the input and output DataInputStream dis = new DataInputStream (s. getInputStream ());
DataOutputStream dos = new DataOutputStream (s. getOutputStream ());
Socket interaction is completed through a stream, that is, the transmitted byte stream, so any file can be transmitted on it. Remember to close it.
We use DataInputStream/DataOutputStream for packaging because we want them to read and write basic data types such as readInt (), writeInt (), readUTF (), writeUTF (), and so on.
Client:
Initiate a socket connection Socket s = new Socket ("192.168.1.200", 8989 );
Obtain the input and output DataInputStream dis = new DataInputStream (s. getInputStream ());
DataOutputStream dos = new DataOutputStream (s. getOutputStream ());
Then you can communicate with each other. Remember to close it.
Http-based
Generally, a request is sent to an application server. In this case, HttpURLConnection is required.
First obtain HttpURLConnection urlConn = new URL ("http://www.google.com"). openConnection ();
Set flag
UrlConn. setDoOutput (true); urlConn. setDoInput (true); // set DoOutput to true in case of post.
UrlConn. setRequestMethod ("POST ");
UrlConn. setUseCache (false); // you can specify whether the cache is used.
UrlConn. setRequestProperty ("Content-type", "application/x-www-form-urlencoded"); // set content-type
Obtain the output stream to facilitate sending information to the server.
DataOutputStream dos = new DataOutputStream (urlConn. getOutputStream ());
Write Request Parameters in the desired stream
Dos. writeBytes ("name =" + URLEncoder. encode ("chenmouren", "gb2312 ");
Dos. flush (); dos. close (); // close immediately after sending.
Get input stream and Data
BufferReader reader = new BufferedReader (new InputStreamReader (urlConn. getInputStream ()));
Reader. readLine (); // use! = Null to determine whether to end
Reader. close ();
After reading, remember to close connection urlConn. disconnect ();
The process Record ends here.