Android Network Programming

Source: Internet
Author: User

I have been working on network programming for the past few days. Here I have sorted out the basic usage of socket network programming and http protocol. Save yourself for later use or study by others.

First, socket-Based Network Programming

Android Network Programming is basically the same as java Network programming. It is basically divided into two types: socket-based and http-based.

The basic Socket-based usage is the same as the usage in Java. Let's briefly review: 1. server 1: Start a server socket: ServerSocket server = new ServerSocket (1234); 2: start listening for requests: Socket client = server. accept (); 3: Get the input and output streams: 4: Then you can use the stream for network transmission. 5: it is best to remember to disable the stream and Server.
ServerSocket server=new ServerSocket(1234);Socket client=server.accept();InputStream in = client.getInputStream();OutputStream out=client.getOutputStream();byte bs[] = new byte[1024];in.read(bs);String str= new String(bs);System.out.println(str);out.write("Server send".getBytes());out.flush();client.close();
2. Client: 1: Initiate a socket connection: Socket server = new Socket ("192.168.1.2", 1234); 2: Get input and output streams: 3: then you can transmit data over the network through a stream. 4: You 'd better remember to close the stream and Socket.
String str = "client send";out.write(str.getBytes());out.flush();byte bs[] = new byte[1024];in.read(bs);System.out.println(new String(bs));server.close();
Of course, this implementation is not good. It should be packaged into upper-layer streams, Reader, and Writer. Server example encapsulated into Reader and Writer:
ServerSocket server=new ServerSocket(1234);Socket client=server.accept();BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));PrintWriter out=new PrintWriter(client.getOutputStream());String str=in.readLine();System.out.println(str);out.println("Server send");out.flush();

Client example encapsulated into Reader and Writer:

Socket server = new Socket("192.168.0.100", 1234);BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));PrintWriter out = new PrintWriter(server.getOutputStream());String str = "client send";out.println(str);out.flush();System.out.println(in.readLine());server.close();
The basic usage of HttpURLConnection Based on Http protocol can be HttpURLConnection or Apache Http operation package. The specific usage is as follows. To enable the application to use the network, you need to add permissions to the Manifest file:
<Uses-permission android: name = "android. permission. INTERNET "/> HttpURLConnection uses the get method by default to interact with the background HttpURLConnection conn = null; try {URL u = new URL (" http: // 192.168.0.100: 8080/test. jsp? Uuid = 123 "); conn = (HttpURLConnection) u. openConnection (); BufferedReader br = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line = ""; while (line = br. readLine ())! = Null) {Log. I ("NetTest", "lien =" + line) ;}} catch (Exception e) {e. printStackTrace ();} finally {conn. disconnect ();}

Note that in Versions later than Android, network processing is not allowed directly in the Activity. We recommend that you use a background thread or simply create a new thread to run it. For example:

Thread t = new Thread (new Runnable () {public void run () {// The code above}); t. start ();

Or:

StrictMode. setThreadPolicy (new StrictMode. threadPolicy. builder (). detectDiskReads (). detectDiskWrites (). detectNetwork () // or //. detectAll () // for // all // detectable // problems. penaltyLog (). build (); StrictMode. setVmPolicy (new StrictMode. vmPolicy. builder (). detectLeakedSqlLiteObjects (). detectLeakedClosableObjects (). penaltyLog (). penaltyDeath (). build (); HttpURLConnection uses Post to interact with the background. The downloaded data is the same as the previous example. The trouble is that you need to set and process the uploaded data to the server, as shown below:
URL u = new URL ("http: // 192.168.0.100: 8080/test. jsp "); conn = (HttpURLConnection) u. openConnection (); // because this is a post request, the following two must be set to trueconn. setDoOutput (true); conn. setDoInput (true); // set conn in POST mode. setRequestMethod ("POST"); // cache conn cannot be used for Post requests. setUseCaches (false); conn. setInstanceFollowRedirects (true); // configure the Content-type of the connection and set it to conn of application/x-www-form-urlencoded. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // DataOutputStream stream DataOutputStream out = new DataOutputStream (conn. getOutputStream (); // String content = "uuid =" + URLEncoder. encode ("post test", "UTF-8"); // write the content to be uploaded into the stream out. writeBytes (content); // refresh and close out. flush (); out. close ();

Use Apache's Http operation package to implement Get-based interaction with the background, for example:

// Encapsulate the method object HttpGet = new HttpGet ("http: // 192.168.0.100: 8080/test. jsp? Uuid = uuid121 & name = name222 "); // create an Http client object HttpClient client = new DefaultHttpClient (); try {// send a request, obtain the returned object HttpResponse response = client.exe cute (get); // obtain the returned value from the response object HttpEntity entity = response. getEntity (); // the stream that gets the returned content. Next, the stream operates InputStream in = entity. getContent (); BufferedReader reader = new BufferedReader (new InputStreamReader (in); StringBuffer buffer = new StringBuffer (); String tempStr =" "; While (tempStr = reader. readLine ())! = Null) {buffer. append (tempStr);} in. close (); // the reader should be written in finally. close (); // The Log should be written in finally. I ("ipvs", buffer. toString ();} catch (Exception err) {err. printStackTrace ();}

Use Apache's Http operation package to implement Post-based interaction with the background, for example:

// Encapsulate the method object HttpPost post = new HttpPost ("http: // 192.168.0.100: 8080/test. jsp "); // The post organization parameter NameValuePair uuid = new BasicNameValuePair (" uuid "," postUuid "); NameValuePair name = new BasicNameValuePair (" name "," postname "); list <NameValuePair> list = new ArrayList <NameValuePair> (); list. add (uuid); list. add (name); // encapsulate these parameters into HttpEntity reqEntity = null; reqEntity = new UrlEncodedFormEntity (list); // then set HttpEntity to post objects. setEntity (reqEntity); // create an Http client object HttpClient client = new DefaultHttpClient (); // send the request and obtain the returned object HttpResponse response = client.exe cute (post );
The processing for obtaining the Entity of response is exactly the same as the get method. I will not go into details here. In actual application development, data transmitted between networks is often in JSON format. XML is not used unless necessary. Therefore, you must master how Android processes JSON data. Android already comes with the JSON Processing Package org. json ". Next let's take a look at how to parse the acquired data. The process of getting the data is the network return value obtained in the previous section. Returns a single object, for example:
JSONObject j = new JSONObject(jsonData);String uuid = j.getString(“uuid");

Returns an array of objects, for example:

JSONArray ja = new JSONArray(jsonData);for(int i=0;i<ja.length();i++){JSONObject j = ja.getJSONObject(i);String retUuid = j.getString("uuid");String retName = j.getString("name");Log.i("javass","ret jsonsss uuid="+retUuid+",name="+retName);}

 

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.