Implementation of Android Network Communication

  • 2021-07-22 11:18:18
  • OfStack

There are two types of Android network programming: http protocol-based and socket-based.
Based on Http protocol: HttpClient, HttpURLConnection, AsyncHttpClient framework, etc.
Based on Socket:
(1) Socket, ServerSocket for TCP/IP
(2) DatagramSocket and DatagramPackage for UDP/IP
(3) Apache Mina Framework
1. Implementation of HttpURLConnection


String response = null; 
Url url = new URL(path); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //  New Connection Instance  
connection.setConnectTimeout(20000);//  Set the connection timeout in milliseconds  
//connection.setReadTimeout(20000);//  Set the timeout for reading data in milliseconds  
connection.setDoInput(true);//  Do you want to open the input stream  true|false 
connection.setRequestMethod("POST");//  Submission 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 the connection port  
int responseCode = conn.getResponseCode(); 
BufferedReader reader = null; 
if (responseCode == 200) { 
  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(); 

2. Implementation of HttpClient


HttpResponse mHttpResponse = null; 
HttpEntity mHttpEntity = null; 
// Create HttpPost Object  
//HttpPost httppost = new HttpPost(path); 
// Settings httpPost Request parameter  
//httppost.setEntity(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 way is passed down httppost  
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
  //  Get the message entity of the response  
  mHttpEntity = mHttpResponse.getEntity(); 
  //  Get 1 Input streams  
  inputStream = mHttpEntity.getContent(); 
  bufReader = new BufferedReader(new InputStreamReader(inputStream));  
  String line = ""; 
  while (null != (line = bufReader.readLine())) { 
    result += line; 
  } 
  //result = EntityUtils.toString(mHttpResponse.getEntity()); 
}  
if (inputStream != null) { 
  inputStream.close(); 
} 
bufReader.close(); 
if (httpClient != null) { 
  httpClient.getConnectionManager().shutdown(); 
} 

3. Implementation of Practical AsyncHttpClient Framework


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) {  
 
  }  
});  

4. 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 Android network communication in several ways of the whole content, I hope to help you learn.


Related articles: