Network Communication Case Analysis of Android

Source: Internet
Author: User
Tags html header

Due to the needs of a project, I studied the network communication mode of android, which is similar to that of the java platform!

The android platform also provides a lot of APIS for developers to use. Please refer to the figure below:

First, we will introduce the communication through the http packet tool in two ways: get and post. The difference between the two is:
1. the post request sends data to the server, and the data is put in the html header and sent to the server url. The data is invisible to the user. The get request adds the parameter value to the url queue, to some extent, this shows that post is more secure than get.
2. The size of data transmitted by get is small. Generally, the size of data transmitted by post is not larger than 2 kb. The default value is unlimited.
To access the network, add the permission <uses-permission android: name = "android. permission. INTERNET"/>
The following is the sample code of the get request for HttpGet: Copy codeThe Code is as follows: View Code
// Create a DefaultHttpClient object
HttpClient httpClient = new DefaultHttpClient ();
// Create an HttpGet object
HttpGet = new HttpGet (
"Http: // 192.168.1.88: 8888/foo/secret. jsp ");
Try
{
// Send a GET request
HttpResponse httpResponse = httpClient.exe cute (get );
HttpEntity entity = httpResponse. getEntity ();
If (entity! = Null)
{
// Read Server Response
BufferedReader br = new BufferedReader (
New InputStreamReader (entity. getContent ()));
String line = null;
Response. setText ("");
While (line = br. readLine ())! = Null)
{
// Use the response text box to display the Server response
Response. append (line + "\ n ");
}
}
}
Catch (Exception e)
{
E. printStackTrace ();
}
}

Sample Code for post request HttpPost:Copy codeThe Code is as follows: View Code
HttpClient httpClient = new DefaultHttpClient ();
HttpPost post = new HttpPost (
"Http: // 192.168.1.88: 8888/foo/login. jsp ");
// If the number of transmitted parameters is large, you can encapsulate the passed parameters.
List <NameValuePair> params = new ArrayList <NameValuePair> ();
Params. add (new BasicNameValuePair ("name", name ));
Params. add (new BasicNameValuePair ("pass", pass ));
Try
{
// Set Request Parameters
Post. setEntity (new UrlEncodedFormEntity (
Params, HTTP. UTF_8 ));
// Send a POST request
HttpResponse response = httpClient
. Execute (post );
// If the server returns a response successfully
If (response. getStatusLine ()
. GetStatusCode () = 200)
{
String msg = EntityUtils
. ToString (response. getEntity ());
// Prompt that the logon is successful
Toast. makeText (HttpClientTest. this,
Msg (5000). show ();
}
}
Catch (Exception e)
{
E. printStackTrace ();
}
}

Next, we will introduce how to use the java package tool for communication and the get and post methods.
The get method is used by default. Sample Code:Copy codeThe Code is as follows: View Code
Try
{
String urlName = url + "? "+ Params;
URL realUrl = new URL (urlName );
// Open the connection with the URL or HttpUrlConnection
URLConnection conn = realUrl. openConnection ();
// Set common request attributes
Conn. setRequestProperty ("accept ","*/*");
Conn. setRequestProperty ("connection", "Keep-Alive ");
Conn. setRequestProperty ("user-agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
// Establish the actual connection
Conn. connect ();
// Obtain all response header fields
Map <String, List <String> map = conn. getHeaderFields ();
// Traverse all response header fields
For (String key: map. keySet ())
{
System. out. println (key + "--->" + map. get (key ));
}
// Define the BufferedReader input stream to read the URL response
In = new BufferedReader (
New InputStreamReader (conn. getInputStream ()));
String line;
While (line = in. readLine ())! = Null)
{
Result + = "\ n" + line;
}
}
Catch (Exception e)
{
System. out. println ("an exception occurred when sending a GET request! "+ E );
E. printStackTrace ();
}
// Use finally blocks to close the input stream

Sample Code for using post:Copy codeThe Code is as follows: View Code
Try
{
URL realUrl = new URL (url );
// Open the connection with the URL
URLConnection conn = realUrl. openConnection ();
// Set common request attributes
Conn. setRequestProperty ("accept ","*/*");
Conn. setRequestProperty ("connection", "Keep-Alive ");
Conn. setRequestProperty ("user-agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
// You must set the following two rows to send a POST request:
Conn. setDoOutput (true );
Conn. setDoInput (true );
// Obtain the output stream corresponding to the URLConnection object
Out = new PrintWriter (conn. getOutputStream ());
// Send Request Parameters
Out. print (params );
// Flush the buffer of the output stream
Out. flush ();
// Define the BufferedReader input stream to read the URL response
In = new BufferedReader (
New InputStreamReader (conn. getInputStream ()));
String line;
While (line = in. readLine ())! = Null)
{
Result + = "\ n" + line;
}
}
Catch (Exception e)
{
System. out. println ("an exception occurred when sending the POST request! "+ E );
E. printStackTrace ();
}

As mentioned above, get requests only require conn. conn must be set for connect () and post requests. setDoOutput (true), conn. setDoinput (true). You must also obtain the output stream getOutputStream () of URLConnection ()
Finally, there are two forms of communication using Sockets (soket): connection-oriented (tcp) and connectionless (udp datagram)
Tcp connection example:Copy codeThe Code is as follows: View Code
// Server
// Create a ServerSocket for listening to client Socket connection requests
ServerSocket ss = new ServerSocket (30000 );
// Uses a loop to continuously accept requests from the client
While (true)
{
// Each time the client Socket request is received, the server also generates a Socket
Socket s = ss. accept ();
OutputStream OS = s. getOutputStream ();
OS. write ("Hello, you have received the message from the server! \ N"
. GetBytes ("UTF-8 "));
// Close the output stream and Socket
OS. close ();
S. close ();
}
// Client
Socket socket = new Socket ("192.168.1.88", 30000 );
// Package the input stream corresponding to the Socket into BufferedReader
BufferedReader br = new BufferedReader (
New InputStreamReader (socket. getInputStream ()));
// Perform common IO operations
String line = br. readLine ();
Show. setText ("data from the server:" + line );
Br. close ();
Socket. close ();

Udp connection example:Copy codeThe Code is as follows: View Code
Server:
Try {
// Create an initramsocket object and specify the listening port number
DatagramSocket socket = new DatagramSocket (4567 );
Byte data [] = new byte [1024];
// Create an empty initrampacket object
DatagramPacket packet = new DatagramPacket (data, data. length );
// Use the receive method to receive data sent by the client
Socket. receive (packet );
String result = new String (packet. getData (), packet. getOffset (), packet. getLength ());
System. out. println ("result --->" + result );
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
Client:
Try {
// First create a initramsocket object
DatagramSocket socket = new DatagramSocket (4567 );
// Create an InetAddree
InetAddress serverAddress = InetAddress. getByName ("192.168.1.104 ");
String str = "hello ";
Byte data [] = str. getBytes ();
// Create an initrampacket object and specify the address to which the packet is sent to the network and the port number.
DatagramPacket packet = new DatagramPacket (data, data. length, serverAddress, 4567 );
// Call the send method of the socket object to send data
Socket. send (packet );
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

The above is my summary. Recently I am working on a file similar to the network video client. If you have done this, you are welcome to propose suggestions and implement other methods for accessing terminals and servers. Thank you!
Everyone !!!

Related Article

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.