Android Network programming network communication Several ways instance share _android

Source: Internet
Author: User
Tags commit soap stringbuffer

Now, mobile apps penetrate all walks of life, the numbers are hard to count, most of them use the web and the interaction with the server is overwhelming, so what are the ways to access the Internet in Android?

Now we've summed up six ways:


(1) For TCP/IP socket, serversocket

(2) Datagramsocket and datagrampackage for UDP. It should be noted that, given that Android devices are usually handheld terminals, IP is distributed over the Internet. It's not fixed. Therefore, the development is also a little different from the ordinary Internet applications.

(3) HttpURLConnection for the direct URL.

(4) Google integrated the Apache HTTP client, you can use HTTP for network programming.

(5) using WebService. Android can support XMLRPC and JSONRPC through open source packages such as Jackson, and can also use KSOAP2 to achieve webservice.

(6) Directly using the WebView View component to display the Web page. Based on WebView Development, Google has provided a web-based Web browser based on Chrome-lite, which allows you to surf the Web directly.

First, socket and ServerSocket

Client code

Copy Code code as follows:

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 (msg) {
Super.handlemessage (msg);
String data = Msg.getdata (). getString ("msg");
Showview.settext ("Message from server:" +data);
}
};
}
@Override
public void OnClick (View v) {
Connecting to a server
if (v = = connectbtn) {
ConnectServer ();
}
Send a message
if (v = = sendbtn) {
String msg = Msgtext.gettext (). toString ();
Send (msg);
}
}
/**
* Ways to connect to the server
*/
public void ConnectServer () {
try {
Socket = new Socket ("192.168.1.100", 4000);
SYSTEM.OUT.PRINTLN ("Connect server succeeded");
Recevie ();
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Connection server failed" +e);
E.printstacktrace ();
}
}
/**
* Ways to send messages
*/
public void Send (String msg) {
try {
PrintStream PS = new PrintStream (Socket.getoutputstream ());
PS.PRINTLN (msg);
Ps.flush ();
catch (IOException e) {

E.printstacktrace ();
}
}
/**
* Read the way the server returns
*/
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 ();

}
}


Ii. Rul, URLConnection, HttpURLConnection, Apachehttp, WebView

Copy Code code as follows:

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) {
  //connect directly using a URL object
  if (v = = CONNECTBTN) {

   try {
    url url = new URL ("Yun_qi_img/image.jpg");
    inputstream is = Url.openstream ();
    bitmap Bitmap = Bitmapfactory.decodestream (IS);
    showimageview.setimagebitmap (bitmap);
   } catch (Exception e) {

    e.printstacktrace ();
   .}

}
Connect directly using the URLConnection object
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 ();
}

}
Connect directly using the HttpURLConnection object
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 ();
}
}
Connecting using the Apachehttp Client (important method)
if (v = = httpclientbtn) {
try {

HttpClient client = new Defaulthttpclient ();
Create the HttpGet object if it is a get commit, otherwise create the HttpPost object
HttpGet HttpGet = new
HttpGet ("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
How post is submitted
HttpPost HttpPost = new HttpPost (
"http://192.168.1.100:8080/myweb/hello.jsp");
If a post commit can encapsulate the parameters in the collection
List dataList = new ArrayList ();
Datalist.add (New Basicnamevaluepair ("username", "AAAAA"));
Datalist.add (New Basicnamevaluepair ("pwd", "123"));
Urlencodedformentity is used to convert a collection to a entity object
Httppost.setentity (New Urlencodedformentity (dataList));
Get the appropriate message
HttpResponse HttpResponse = Client.execute (HttpPost);
Get message Content
httpentity entity = httpresponse.getentity ();
Converts a message object directly to a string
String content = entityutils.tostring (entity);
Showtextview.settext (content);

To parse a Web page by WebView
Webview.loaddatawithbaseurl (NULL, Content, "text/html", "Utf-8", null);
To parse a point URL
Webview.loadurl (URL);
catch (Clientprotocolexception e) {

E.printstacktrace ();
catch (IOException e) {

E.printstacktrace ();
}
}
}

}

Iii. Use of WebService

Copy Code code as follows:

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) {
To create a WebService connection object
Httptransportse httpse = new Httptransportse (Service_url);
Get envelop via SOAP1.1 protocol object
Soapserializationenvelope envelop = new Soapserializationenvelope (SOAPENVELOPE.VER11);
To create a SOAP object based on the namespace and method name
Soapobject soapobject = new Soapobject (NAMESPACE, "validate");
Passing parameters to the calling method
Soapobject.addproperty ("arg0", "abc");
Soapobject.addproperty ("Arg1", "123");
To set the Soapobject object as an outgoing SOAP message for a Soapserializationenvelope object
Envelop.bodyout = Soapobject;
try {
Start calling a remote method
Httpse.call (null, envelop);
Gets the SOAP object returned by the remote method
Soapobject resultobj = (soapobject) Envelop.bodyin;
According to the key named return to get the value inside, this is the value of the method
String returnstr = Resultobj.getproperty ("return"). ToString ();
Toast.maketext (This, "return value:" +returnstr, Toast.length_long). Show ();
catch (IOException e) {

E.printstacktrace ();
catch (Xmlpullparserexception e) {

E.printstacktrace ();
}

}

}
}

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.