android network programming network communication several ways of example sharing

  • 2020-05-19 05:48:52
  • OfStack

Nowadays, mobile applications have penetrated into all walks of life, and the number of them is countless. Most of them will use the network, and the interaction with the server is overwhelming. So what are the ways to access the network in android?

Here are six ways to do it:


(1) Socket and ServerSocket for TCP/IP

(2) DatagramSocket and DatagramPackage for UDP. It is important to note here that, given that Android devices are usually handheld,IP is distributed along with the Internet. It's not fixed. Therefore, development is also different from ordinary Internet applications in one point.

(3) HttpURLConnection for direct URL.

(4) Google integrates Apache HTTP client and can use HTTP for network programming.

(5) use WebService. Android can support Xmlrpc and Jsonrpc through open source packages such as jackson, or Ksoap2 can be used to implement Webservice.

(6) directly use the WebView view component to display web pages. Based on WebView, Google already offers an Web browser based on chrome-lite that lets you browse the web directly.

1. socket serverSocket

Client code


public class TestNetworkActivity extends Activity implements OnClickListener{
 private Button connectBtn;
 private Button sendBtn;
 private TextView showView;
 private EditText msgText;
 private Socket socket;
 private Handler handler;
 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.test_network_main);
  connectBtn = (Button) findViewById(R.id.test_network_main_btn_connect);
  sendBtn = (Button) findViewById(R.id.test_network_main_btn_send);
  showView = (TextView) findViewById(R.id.test_network_main_tv_show);
  msgText = (EditText) findViewById(R.id.test_network_main_et_msg);
  connectBtn.setOnClickListener(this);
  sendBtn.setOnClickListener(this);

  handler = new Handler(){
   @Override
   public void handleMessage(Message msg) {
    super.handleMessage(msg);
    String data = msg.getData().getString("msg");
    showView.setText(" Message from the server :"+data);
   }
  };
 }
 @Override
 public void onClick(View v) {
  // Connect to server 
  if(v == connectBtn){
   connectServer();
  }
  // Send a message 
  if(v == sendBtn){
   String msg = msgText.getText().toString();
   send(msg);
  }
 }
       /** 
  * The method to connect to the server 
  */
 public void connectServer(){
  try {
   socket = new Socket("192.168.1.100",4000);
   System.out.println(" Connection to server successful ");
   recevie();
  } catch (Exception e) {
   System.out.println(" Connection to server failed "+e);
   e.printStackTrace();
  } 
 }
       /**
  * The method to send the message 
  */
 public void send(String msg){
  try {
   PrintStream ps = new PrintStream(socket.getOutputStream());
   ps.println(msg);
   ps.flush();
  } catch (IOException e) {

   e.printStackTrace();
  }
 }
       /**
  * Reads the method returned by the server 
  */
 public void recevie(){
  new Thread(){
   public void run(){
    while(true){
     try {
      InputStream is = socket.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String str = br.readLine();
      Message message = new Message();
      Bundle bundle = new Bundle();
      bundle.putString("msg", str);
      message.setData(bundle);
      handler.sendMessage(message);

     } catch (IOException e) {

      e.printStackTrace();
     }
    }
   }
  }.start();

 }
}


2. RUL, URLConnection, httpURLConnection, ApacheHttp, WebView


public class TestURLActivity extends Activity implements OnClickListener {
 private Button connectBtn;
 private Button urlConnectionBtn;
 private Button httpUrlConnectionBtn;
 private Button httpClientBtn;
 private ImageView showImageView;
 private TextView showTextView;
 private WebView webView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.test_url_main);
  connectBtn = (Button) findViewById(R.id.test_url_main_btn_connect);
  urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
  httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
  httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
  showImageView = (ImageView) findViewById(R.id.test_url_main_iv_show);
  showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
  webView = (WebView) findViewById(R.id.test_url_main_wv);
  connectBtn.setOnClickListener(this);
  urlConnectionBtn.setOnClickListener(this);
  httpUrlConnectionBtn.setOnClickListener(this);
  httpClientBtn.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
  //  Direct use of URL Object to connect 
  if (v == connectBtn) {

   try {
    URL url = new URL("http://192.168.1.100:8080/myweb/image.jpg");
    InputStream is = url.openStream();
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    showImageView.setImageBitmap(bitmap);
   } catch (Exception e) {

    e.printStackTrace();
   }
  }
  //  Direct use of URLConnection Object to connect    
  if (v == urlConnectionBtn) {
   try {

    URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    byte[] bs = new byte[1024];
    int len = 0;
    StringBuffer sb = new StringBuffer();
    while ((len = is.read(bs)) != -1) {
     String str = new String(bs, 0, len);
     sb.append(str);
    }
    showTextView.setText(sb.toString());
   } catch (Exception e) {

    e.printStackTrace();
   }
  }
  //  Direct use of HttpURLConnection Object to connect 
  if (v == httpUrlConnectionBtn) {

   try {
    URL url = new URL(
      "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
    HttpURLConnection connection = (HttpURLConnection) url
      .openConnection();
    connection.setRequestMethod("GET");
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
     String message = connection.getResponseMessage();
     showTextView.setText(message);
    }
   } catch (Exception e) {

    e.printStackTrace();
   }
  }
  //  use ApacheHttp The client connects ( Important method )
  if (v == httpClientBtn) {
   try {

    HttpClient client = new DefaultHttpClient();
    //  If it is Get Commit to create HttpGet Object, otherwise created HttpPost object 
    // HttpGet httpGet = new
    // HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
    // post Method of submission 
    HttpPost httpPost = new HttpPost(
      "http://192.168.1.100:8080/myweb/hello.jsp");
    //  If it is Post A submission can be passed as a parameter wrapped in a collection 
    List dataList = new ArrayList();
    dataList.add(new BasicNameValuePair("username", "aaaaa"));
    dataList.add(new BasicNameValuePair("pwd", "123"));
    // UrlEncodedFormEntity Used to convert a collection to Entity object 
    httpPost.setEntity(new UrlEncodedFormEntity(dataList));
    //  Get the corresponding message 
    HttpResponse httpResponse = client.execute(httpPost);
    //  Get message content 
    HttpEntity entity = httpResponse.getEntity();
    //  Converts the message object directly to a string 
    String content = EntityUtils.toString(entity);
                                //showTextView.setText(content);

    // through webview To parse web pages 
    webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
    // To the point url To parse 
    //webView.loadUrl(url);
   } catch (ClientProtocolException e) {

    e.printStackTrace();
   } catch (IOException e) {

    e.printStackTrace();
   }
  }
 }
}

3. Use webService


public class LoginActivity extends Activity implements OnClickListener{
 private Button loginBtn;
 private static final String SERVICE_URL = "http://192.168.1.100:8080/loginservice/LoginServicePort";
 private static final String NAMESPACE = "http://service.lovo.com/";
 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.login_main);
  loginBtn = (Button) findViewById(R.id.login_main_btn_login);
  loginBtn.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {

  if(v == loginBtn){
   // create WebService Connection object of 
   HttpTransportSE httpSE = new HttpTransportSE(SERVICE_URL);
   // through SOAP1.1 Protocol object envelop
   SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
   // Create by namespace and method name SOAP object 
   SoapObject soapObject = new SoapObject(NAMESPACE, "validate");
   // Pass parameters to the calling method 
   soapObject.addProperty("arg0", "abc");
   soapObject.addProperty("arg1","123");
   // will SoapObject Object set to SoapSerializationEnvelope Object outgoing SOAP The message 
   envelop.bodyOut = soapObject;
   try {
    // Start calling remote methods 
    httpSE.call(null, envelop);
    // Get the one returned by the remote method SOAP object 
    SoapObject resultObj = (SoapObject) envelop.bodyIn;
    // According to the called return To get the inside value, which is the method's return value 
    String returnStr = resultObj.getProperty("return").toString();
    Toast.makeText(this, " The return value: "+returnStr, Toast.LENGTH_LONG).show();
   } catch (IOException e) {

    e.printStackTrace();
   } catch (XmlPullParserException e) {

    e.printStackTrace();
   }

  }

 }
}


Related articles: