Android Network communication Resolution

Source: Internet
Author: User
Tags html header rfc

The purpose of network programming is to abstain indirectly from communicating with other computers through network protocols. There are two main problems in the network programming, one is how to locate the network on a ring more than one station, and the other is how to reliably and efficiently transmit data after locating the host. At present, the most widely used Internet protocol is TCP/IP protocol: In the TCP/IP protocol, it is mainly responsible for the location of network host, the routing of data transmission, and the IP address can uniquely determine a host on the Internet. The TCP layer provides a reliable application-oriented data transmission mechanism, which is the main object of network programming, and generally does not need to care about how the IP layer handles the data. The Android platform provides a rich API for network communications, adding android.net, android.net.http packages In addition to the java.net, javax.net, Javax.net.ssl packages reserved for the Java standard platform. In addition, the Android platform also includes Apache-owned HTTP communication-related ORG.APACHE.HTTP packages into the system. The following is an introduction. 1) java.net Package main class/Interface description class/interface                           Description Serv Ersocket                 represents the socket for the service that waits for a client connection Scoket         &NBS P             provides a client-side TCP socket Datagramsocket               to implement a For sending and receiving data Bao de DUP sockets datagrampacket               packet intetaddress       &NBS P         represents IP address unkownhostexception         Location host exception HttpurlconnectioN           Resource Connection Manager URLs for managing HTTP links (RFC 2068)               &NBS P         location information for the specified 1 resources on the Internet (RFC 1783) 2) JAVAX.NET.SSL Package main class/Interface description class/interface           & nbsp               Description httpsurlconnection           for managing HTTPS connections (RFC 281 8) Resource Connection Manager sslsocket                   provide secure protocol sockets Sslserversocket             secure service sockets based on SSL, TLS, and other protocols Sslcontext                   SSL context apitrustmanagerfactory         Trust manager factory Keymanagerfactory           key Manager Factory Org.apacke.http.impl.client Package main class/Interface description class/interface                     &NBSP ;     Description defaulthttpclient           Represents an HTTP client default implementation interface for the main class/Interface description class/interface in the Org.apacke.http.client.methods package   &nbsp                       Description Httpget/httppost/httpput/httphead represents various HTTP Method Org.apacke.http Package Main class/Interface description class/interface                         Description HttpResponse                 An HTTP response statusline         &NBSP ;         status line header                       indicates HTTP header word Section headerelement               HTTP header value One element namevaluespair         &N Bsp     Encapsulates a property: class of value pairs httpentity                   An entity that can be received or sent with an HTTP message for more information about this: Refer to the Android SDK first to introduce HTTP communication through the HTTP package tool provided by Apache, in two forms: get and post. There are several main differences between GET and POST requests: 1. The POST request can transmit data to the server, and the data is sent to the service-side URL address together with the HTML header, and the data is not visible to the user. The get is to add the parameter data queue to the URL of the submission, the value and the form in each field one by one corresponding to, for example (Http://sso.eoeandroid.com/sso.php?partner=tiangu) 2, get the amount of data transmitted less, not more than 2KB.Post transmits a large amount of data, which is generally not restricted by default. 3, get security is very low, post security is high. 1, first add permission: 2, New HttpClient object, and do time-out settings: httpclienthttpclient= newdefaulthttpclient (); New HttpClient Object Httpconnectionparams.setconnectiontimeout (Httpclient.getparams (), 3000); Set the connection Timeout Httpconnectionparams.setsotimeout (Httpclient.getparams (), 3000); Set the data read time timeout connmanagerparams.settimeout (Httpclient.getparams (), 3000); Set the fetch connection timeout from the connection pool to 3, use the GET request, and get the HttpResponse response: httpgethttpget= newhttpget (URL); Get Request Httpresponseresponse = Httpclient.execute (HttpGet); Executes the request and gets the response result if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//response via string result= Entityutils.tostring (Response.getentity (), "UTF-8");} Note Do exception handling 4, use POST request, and get HttpResponse response: httpclienthttpclient= newdefaulthttpclient (); New HttpClient object httpposthttppost= newhttppost (URL); New HttpPost Object list params= newarraylist (); Use Namevaluepair to save the post parameters to be passed Params.add (Newbasicnamevaluepair ("username", "hello")); Add the parameters to be passed Params.add (Newbasicnamevaluepair ("Password", "EoE")); try{httpentityentity =Newurlencodedformentity (params, HTTP. UTF_8); Sets the character set httppost.setentity (entity); Set the parameter entity httpresponsehttpresp= Httpclient.execute (HttpPost); Gets the HttpResponse instance if (Httpresp.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {//response via string result = Entityutils.tostring (Httpresp.getentity (), "UTF-8");} The else{//response did not pass through}}catch{} and then introduced the use of standard Java interfaces for HTTP communication in two forms: get and post. 1, its default use GET request: URL pathurl= newurl (URL); Create a URL object httpurlconnectionurlconnect= (httpurlconnection) pathurl.openconnection (); Open a HttpURLConnection connection urlconnect.setconnecttimeout (3000); Set the connection timeout time urlconnect.connect (); Inputstreamreaderin = Newinputstreamreader (Urlconnect.getinputstream ()); Get read Content Bufferedreaderbuffer = Newbufferedreader (in); Create bufferedreaderstring inputline= null;while for Output (((inputline= buffer.readline ()) = null)) {//Use loops to read data}2, Use POST request: String params= "username=" + urlencoder.encode ("Hello", "UTF-8") + "&password=" + urlencoder.encode ("EoE", "UTF-8"); byte[] Postdata= params.getbytes (); URL pathurl= newurl (UrL); Create a URL object httpurlconnectionurlconnect= (httpurlconnection) pathurl.openconnection (); Urlconnect.setconnecttimeout (3000); Set the connection timeout time urlconnect.setdooutput (true); The POST request must be set to allow output urlconnect.setusecaches (false); The POST request cannot use the cache Urlconnect.setrequestmethod ("post"); Set the post mode request urlconnect.setinstancefollowredirects (TRUE); Urlconnect.setrequestproperty ("Content-type", " Application/x-www-form-urlencode ");//Configuration Request Content-typeurlconnect.connect (); Start Connection Dataoutputstreamdos = Newdataoutputstream (Urlconnect.getoutputstream ()); Send request parameter Dos.write (postdata);d Os.flush ();d os.close (); if (urlconnect.getresponsecode () = = 200) {//request succeeded byte[] data = Readinputstream (Urlconnect.getinputstream ());} Sockets are often referred to as a "socket", an abstraction layer through which an application sends and receives data, just as an application opens a file handle to read and write data to a stable memory. Using sockets, you can add applications to your network and communicate with other applications that are on the same network. The information written to the socket by an application on one computer can be read by another application on another computer, and vice versa. There are two main ways to operate a socket: a connection-oriented (stream socket) and a non-connected (datagram socket). A connection-oriented socket operation must establish a connection and a call in which all packets arrive in the same order and in the order in which they are sent, using the TCP protocol, at which point the socket must be connected to the socket of the destination before the data is sent, inefficient but secure; no connection SockeT operation, packet arrival order and emit order are not guaranteed to be consistent. Using the UDP protocol, a datagram is a separate unit that contains all the information about the delivery, fast, efficient, but not very secure. If the reliability of the data is more important, the use of connection-oriented operations is recommended. 1, Server side: Serversocketss=newserversocket (8888); Create a ServerSocket object and let this ServerSocket listen while (true) {Socket socket=ss.accept () on port 8888 and//Call the Accept () method of ServerSocket , accept the request sent by the client, if the client does not send the data, then the thread will not continue to Try{datainputstreamin=newdatainputstream (Socket.getinputstream ()); Receive client information string Readline=in.readutf (); System.out.println (ReadLine);D Ataoutputstreamout=newdataoutputstream (Socket.getoutputstream ()); Send Message to Client OUT.WRITEUTF ("Link server success"); Out.flush (); In.close (); Close stream Out.close ();//Close stream socket.close ();//Close open Socket} catch{}}1, client: Socket = Newsocket ("192.168.0.37", 8888);// Create socket with IP address for my PC machine address, mobile phone via wifi internet and server in one segment dataoutputstreamout = Newdataoutputstream (Socket.getoutputstream ()) ; Send Message Out.writeutf (sendmsg) to Server, Out.flush ();D atainputstreamin = Newdatainputstream (Socket.getinputstream ()); Receives a message from the server string readmsg= In.readutf (); if (readmsg!= null) {Text.settext (readmsg);} Out.close (); In.close ();Socket.close (); The steps to create the server are as follows: 1, specify a port to instantiate a serversocket;2, call ServerSocket's accept method to cause blocking while waiting for the connection; 3. Get the socket stream at the bottom to read and write, 4, encapsulate the data into a stream, 5, read and write the socket, 6, close the open stream. The steps to create the client are as follows: 1. Instantiate the socket via IP address and port, request a connection server, 2, get the stream on the socket for reading and writing, 3, wrap the stream into the input/output (for example: bufferedreader/ PrintWriter Dataoutputstream/datainputstream, etc.); 4. Read and write the socket; 5. Close the open stream.

Android network traffic resolution

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.