The realization Way of Android network communication _android

Source: Internet
Author: User
Tags readline throwable stringbuffer

Android network programming is divided into two types: HTTP protocol based, and socket based.
HTTP protocol based : HttpClient, HttpURLConnection, asynchttpclient framework, etc.
Based on the socket :
(1) socket, ServerSocket
for TCP/IP (2) for UDP/IP Datagramsocket, Datagrampackage
(3) Apache mina framework
One, httpurlconnection implementation

String response = null; 
URL url = new URL (path); HttpURLConnection connection = (httpurlconnection) url.openconnection (); Create a new Connection instance connection.setconnecttimeout (20000);/Set the connection timeout, the unit millisecond//connection.setreadtimeout (20000), or set the read data timeout time, The unit millisecond connection.setdoinput (TRUE);//whether to open the input stream true|false connection.setrequestmethod ("POST");//Submit Method post| 
Get//connection.setusecaches (FALSE);//whether to cache True|false//connection.setrequestproperty ("Accept", "*/*"); 
Connection.setrequestproperty ("Connection", "keep-alive"); 
Connection.setrequestproperty ("Charset", "UTF-8"); 
Connection.setrequestproperty ("Content-length", String.valueof (Data.length)); 
Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); 
Connection.connect ()//Open connection port int responsecode = Conn.getresponsecode (); 
BufferedReader reader = null; 
  if (Responsecode = =) {reader = new BufferedReader (New InputStreamReader (Connection.getinputstream (), "Utf-8")); StringBuffer buffer = new StringbuFfer (); 
  String line = ""; 
  while (line = Reader.readline ())!= null) {buffer.append (line); 
} response = Buffer.tostring (); 
else {response = "return code:" +responsecode; 
} reader.close (); 
 Conn.disconnect ();

Two, httpclient implementation

HttpResponse mhttpresponse = null; 
Httpentity mhttpentity = null; 
Create HttpPost object//httppost httppost = new HttpPost (path); Sets the HttpPost request parameter//httppost.setentity (the new urlencodedformentity (params,http). 
Utf_8));   
HttpGet httpget = new HttpGet (path); 
HttpClient httpclient = new Defaulthttpclient (); 
InputStream inputstream = null; 
BufferedReader bufreader = null; 
String result = ""; Send the request and get the response object mhttpresponse = Httpclient.execute (httpget);//If it is "POST" the HttpPost if (Mhttpresponse.getstatusline () 
  . Getstatuscode () = = HTTPSTATUS.SC_OK) {//Get the response of the message entity mhttpentity = Mhttpresponse.getentity (); 
  Gets an input stream inputstream = Mhttpentity.getcontent ();  
  Bufreader = new BufferedReader (new InputStreamReader (InputStream)); 
  String line = ""; 
  while (the null!= (line = Bufreader.readline ())} {result + = line; 
}//result = Entityutils.tostring (Mhttpresponse.getentity ()); 
} if (InputStream!= null) {inputstream.close (); 
} bufreader.close (); if (httpclient!= null) {Httpclient.getconnectionmanager (). Shutdown (); 
 }

Three, practical asynchttpclient framework Realization Way

Asynchttpclient client = new Asynchttpclient ();  
Client.get (URL, new Asynchttpresponsehandler () {  
  @Override public  
  void onsuccess (int i, header[] headers, byte[ ] {bytes) {        
    String response = new String (bytes, 0, bytes.length, "UTF-8");            
  }  
  @Override public  
  void onfailure (int i, header[] headers, byte[] bytes, throwable throwable) {  
 
  }  
});  

Use the WebView view component to display a Web page

Mywebview.getsettings (). Setjavascriptenabled (true);  
Mywebview.setwebviewclient (New Webviewclient () {  
  @Override public  
  boolean shouldoverrideurlloading ( WebView view, String URL) {  
    view.loadurl (URL);  
    return true;  
  }  
});  
Mywebview.loadurl ("http://" +networkaddress);  

The above is the entire content of network communication in Android, hope to be helpful to everybody's study.

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.