<span id="Label3"></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">In Android network communication, the socket is usually used for data communication between devices, and HTTP is used to request the network Data.<br><span style="white-space:pre"></span>1. Socket (socket Socket)<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">Whether it is a Java development experience Or. NET development experience of the students should have a more or less understanding of the socket, the common TCP or UDP protocol is actually based on the socket to Achieve.<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">A socket is a process or application used to describe a device on a network, and the socket consists of an IP address and a port number. The IP address is used to locate the device, and the port number is used to locate the application or process, such as our common HTTP protocol running on port 80. The common format for sockets is: 192.168.1.1:1234.<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">So how does an application communicate with other devices on the network through a socket? typically, the socket communication has two parts, part of the server side of the listener, and part of the client side of the active request Connection. The server side listens to the port in the socket until there is a request, and when the client makes a connection request to the port, the server responds and returns a socket OBJECT. Later on the server side and client side of the data exchange can use this socket to Operate.<br><span style="white-space:pre"></span>2. Using the socket for data exchange in Android<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">ServerSocket<br>When establishing a server, you need to use the ServerSocket object, which automatically listens for the port number passed in its constructor, and returns a connected socket object using the Serversocket.accept () method after receiving a connection Request. This method doesn't need us to be like. net, which uses the start method, it will listen automatically.<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">Socket<br>You need to use the socket class regardless of whether you are establishing a client or doing other data exchange Operations. The socket class needs to access the Server-side IP address and port number when initializing, and returns a socket object connected to the server side, which returns an exception if the connection Fails. With serversocket, It is also an automatic connection Request.<br></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px; font-family:Arial; line-height:26px">and returns a socket object connected to the server side, and if the connection fails, an exception is Returned. With serversocket, It is also an automatic connection Request.</p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-size:14px"><span style="font-family:Arial"><span style="line-height:26px">With the above two steps, the server side and client side can be connected, but only the connection does not have any effect, the data exchange is our goal, this time need to use the IO stream in the OutputStream class and the InputStream class.</span></span><br><span style="font-family:Arial"><span style="line-height:26px">Outputstream--writable Stream</span></span><br><span style="font-family:Arial"><span style="line-height:26px">You can use the data flow that is returned by the Socket.getoutputstream () method when the application needs a stream for data write Operations.</span></span><br><span style="font-family:Arial"><span style="line-height:26px">Inputstream--readable Stream</span></span><br></p></p><p style="font-family:Arial; line-height:26px"><p style="font-family:Arial; line-height:26px">When an application wants to fetch data from a stream, it can use the data flow returned by the Socket.getinputstream () method.</p></p><p style="font-family:Arial; line-height:26px"><p style="font-family:Arial; line-height:26px"></p></p><pre name="code" class="java">View Code Package lib.demo; Import java.io.BufferedReader; Import java.io.BufferedWriter; Import java.io.IOException; Import java.io.InputStreamReader; Import java.io.OutputStreamWriter; Import java.net.ServerSocket; Import java.net.Socket; public class Sockethelper {private static ServerSocket ServerSocket = null; private static Socket client = null; Private final static int port = 9048; private static BufferedReader br= null; private static BufferedWriter bw = null; /** * Create a Socketserver object used to establish the server * @throws ioexception */public static void Createserver () throws Ioexceptio n {serversocket = new ServerSocket (port,10); System.out.println ("start Listening ..."); /** * Create a Socket object used to connect the Socketserver object * @param the IP address of the DstName server object * @return * @throws IO Exception */public static sockets CreateClient (String Dstname) throws IOException {socket socket = new SO Cket (dstname, Port); Socket sockets = new Socket ("192.168.8.12", port); Return socket; }/** * Returns a socket object that is already connected to the server * @throws ioexception */public static void Getclinetsocket () throws IOException {client = serversocket.accept (); System.out.println ("get a connected client"); }/** * Send data to the stream fetched by the socket object * @param socket * @param msg * @throws IOException */public static void sendmsg (socket socket, String msg) throws IOException {BW = new BufferedWriter (new OUTPUTSTREAMW Riter (socket.getoutputstream ())); Bw.write (msg); Bw.flush (); Bw.close (); /** * Gets the data in the socket object stream * @param socket * @param msg * @return * @throws IOException * * public static string Receivemsg (socket socket, string Msg) throws IOException {br = new BufferedReader (new InputStreamReader (socket.getinputstream ())); String receivemsg = "receIve msg: "+ br.readline (); Br.close (); Return receivemsg; /** * Release Socket Object * @throws ioexception */public static void Close () throws IOException { If (client! = Null) {client.close (); } If (serversocket! = Null) {serversocket.close (); } } }</pre><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">3. HTTP Communication</span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">before you begin, Let's briefly describe two different requests in the HTTP Protocol--get and Post. The Get method appends data to the server after the data request, such as Common: the Http://XXX.XXX.XXX/XX.aspx?id=1,POST method is to put the requested data into the HTTP request header, as part of the request header to the Server. therefore, before HTTP programming, the first thing to do is to identify exactly which method to use for data requests. </span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">in android, There are two ways to do HTTP programming: 1, httpurlconnection;2, HttpClient. </span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">HttpURLConnection</span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">HttpURLConnection is an abstract class that inherits from urlconnection, when programming in http, the class from HttpURLConnection is the basis for all operations, and the code to get the object is as Follows:</span></span><p><p></p></p><p><p><span style="font-family:Helvetica,Tahoma,Arial,sans-serif"><span style="line-height:25.2000007629395px"></span></span></p></p><pre name="code" class="java"><pre name="code" class="java">View Code public httpurlconnection urlconn= null; private void Init () throws IOException { if (urlstr== "") { urlstr= "http://www.baidu.com"; } URL url = new URL (urlstr); Open a URL that points to the connection object urlconn = (httpurlconnection) url.openconnection (); }</pre></pre><span style="font-family:Arial; font-size:14px; line-height:26px"><span style="font-family:Arial; font-size:14px; line-height:26px">HttpURLConnection requests for network resources use get mode by default, so we do not need to do too much work when we use get mode:</span></span><p><p></p></p><p><p><span style="font-family:Arial"><span style="line-height:26px"></span></span></p></p><pre name="code" class="java"><pre name="code" class="java">View Code public httpurlconnection urlconn= null; private void Init () throws IOException { if (urlstr== "") { urlstr= "http://www.baidu.com"; } URL url = new URL (urlstr); Open a URL that points to the connection object urlconn = (httpurlconnection) url.openconnection (); } /** * GET request in http, with the requested parameter in the url, the URL format of the request is usually: "http://XXX. Xxxx.com/xx.aspx?param=value " * The default HTTP request in Android is get mode * @return * @throws ioexception */ Public String Httpgetmethod () throws IOException { if (urlconn = = Null) { Init (); } String result = Streamdeal (urlconn.getinputstream ()); Urlconn.disconnect (); return result; }</pre></pre><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">when we need to use the post method, we need to use Setrequestmethod () to set the request Mode. </span></span><p><p></p></p><p><p> <span style="font-family:helvetica,tahoma,arial,sans-serif"><span style="line-height:25.2000007629395px"> </span> /span> </span></p></p><pre name="code" class="java">The POST request in the View Code/** * HTTP does not append any parameters to the url, and these parameters are transferred to the server in the form of a key-value pair, such as a cookie or session key=value, to complete a request * request U The RL format is usually: "http://XXX. xxxx.com/xx.aspx "* @param param requested key name * @param value requested data value * @throws ioexception */public String Htt Ppostmethod (String key,string Value) throws IOException {if (urlconn==null) {Init (); }//set the URLConnection readable urlconn.setdoinput (true); Set the URLConnection writable Urlconn.setdooutput (true); Use the Post method to submit data Urlconn.setrequestmethod ("post"); Do not run cache urlconn.setusecaches (false); When a data request is made using post, we can manually perform the Connect action, which, of course, is performed by default in the Getoutputstream () method, which sets the action of the URLConnection property, Be sure to do this before the connect action, because once the action has been executed, the familiar settings will not have any effect urlconn.connect (); When we use post, we need to construct the contents of some HTTP requests ourselves, so we need to use OutputStream to write data like outputstreamwriter writer = new OutputStreamWriter (u Rlconn.getoutputstream ()); String URLQuerystr = key+ "=" +urlencoder.encode (value, "Utf-8"); Writer.write (urlquerystr); Writer.flush (); Writer.close (); Gets the contents of the returned String result = Streamdeal (urlconn.getinputstream ()); Return result; }</pre><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">HttpClient</span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">This class is not from android, but from ORG.APACHE.HTTP. As with httpurlconnection, HttpClient also has get and post two Ways. </span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">HttpGet</span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">in httpclient, we can easily use the HttpGet object to get a data request operation by getting, and when we get the HttpGet object we can use the HttpClient Execute method to send a request to our Server. When the GET request is sent by the server, a HttpResponse response object is returned, and we can get the status code that responds back, such as: 200, 400, 401, and so On. </span></span><p><p></p></p><p><p><span style="font-family:Helvetica,Tahoma,Arial,sans-serif"><span style="line-height:25.2000007629395px"></span></span></p></p><pre name="code" class="java"><pre name="code" class="java">View Code public String httpgetmethod () { string result = ""; Try { HttpGet HttpRequest = new HttpGet (urlstr); HttpClient HttpClient = new Defaulthttpclient (); HttpResponse HttpResponse = Httpclient.execute (httprequest); If (httpresponse.getstatusline (). getstatuscode () ==httpstatus.sc_ok) { result = entityutils.tostring ( Httpresponse.getentity ()); } else { result = "null"; } return result; } Catch (Exception e) { return null; } }</pre></pre><br><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><span style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px">HttpPost</span></span><br style="font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><p><p></p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Helvetica,Tahoma,Arial,sans-serif; font-size:14px; line-height:25.2000007629395px"><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:helvetica,tahoma,arial,sans-serif; font-size:14px; line-height:25.2000007629395px "> When we use the post method, we can use the HttpPost class to Operate. When we get the HttpPost object, we need to pass in the Key-value pair to the request body, which we can construct using the Namevaluepair object, and then use the HttpRequest object to construct our request body Eventually. finally, We use Httpclient's Execute method to send our request and return a HttpResponse object after the response is Received. The other actions are the same as we do in the HttpGet Object. </p></p><pre name="code" class="java">View Code public String httppostmethod (string key,string value) {string result = ""; Try {//httppost Connection object HttpPost HttpRequest = new HttpPost (urlstr); Use Namevaluepair to save the post parameter to be passed list<namevaluepair> params = new arraylist<namevaluepair> (); Add the parameter params.add to be passed (new Basicnamevaluepair (key, value)); Sets the character set httpentity httpentity = new Urlencodedformentity (params, "Utf-8"); Request HttpRequest httprequest.setentity (httpentity); Get the default HttpClient HttpClient HttpClient = new Defaulthttpclient (); Obtained httpresponse HttpResponse HttpResponse = Httpclient.execute (httprequest); HTTPSTATUS.SC_OK indicates successful connection if (httpresponse.getstatusline (). getstatuscode () = = Httpstatus.sc_ok) {//fetch The string to return result = Entityutils.tostring (httpresponse.getentity ()); Return result; } else {rEturn "null"; }} catch (Exception e) {return null; } }</pre><br><br><br><br><br><br><p><p>Android Network Programming Socket Http</p></p></span>
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