Android之网络编程之网络通信几种方式实例分享

举报
chenyu 发表于 2021/07/26 23:43:24 2021/07/26
【摘要】                                       这篇文章主要介绍了android 网络编程之网络通信几种方式,有需要的朋友可以参考一下   &n...

                                      这篇文章主要介绍了android 网络编程之网络通信几种方式,有需要的朋友可以参考一下

                          现在总结了六种方式:

(1)针对TCP/IP的Socket、ServerSocket

(2)针对UDP的DatagramSocket、DatagramPackage。这里需要注意的是,考虑到Android设备通常是手持终端,IP都是随着上网进行分配的。不是固定的。因此开发也是有一点与普通互联网应用有所差异的。

(3)针对直接URL的HttpURLConnection。

(4)Google集成了Apache HTTP客户端,可使用HTTP进行网络编程。

(5)使用WebService。Android可以通过开源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去实现Webservice。

(6)直接使用WebView视图组件显示网页。基于WebView 进行开发,Google已经提供了一个基于chrome-lite的Web浏览器,直接就可以进行上网浏览网页。

一、socket与serverSocket

客户端代码


   
  1. public class TestNetworkActivity extends Activity implements OnClickListener{
  2. private Button connectBtn;
  3. private Button sendBtn;
  4. private TextView showView;
  5. private EditText msgText;
  6. private Socket socket;
  7. private Handler handler;
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.test_network_main);
  12. connectBtn = (Button) findViewById(R.id.test_network_main_btn_connect);
  13. sendBtn = (Button) findViewById(R.id.test_network_main_btn_send);
  14. showView = (TextView) findViewById(R.id.test_network_main_tv_show);
  15. msgText = (EditText) findViewById(R.id.test_network_main_et_msg);
  16. connectBtn.setOnClickListener(this);
  17. sendBtn.setOnClickListener(this);
  18. handler = new Handler(){
  19. @Override
  20. public void handleMessage(Message msg) {
  21. super.handleMessage(msg);
  22. String data = msg.getData().getString("msg");
  23. showView.setText("来自服务器的消息:"+data);
  24. }
  25. };
  26. }
  27. @Override
  28. public void onClick(View v) {
  29. //连接服务器
  30. if(v == connectBtn){
  31. connectServer();
  32. }
  33. //发送消息
  34. if(v == sendBtn){
  35. String msg = msgText.getText().toString();
  36. send(msg);
  37. }
  38. }
  39. /**
  40. *连接服务器的方法
  41. */
  42. public void connectServer(){
  43. try {
  44. socket = new Socket("192.168.1.100",4000);
  45. System.out.println("连接服务器成功");
  46. recevie();
  47. } catch (Exception e) {
  48. System.out.println("连接服务器失败"+e);
  49. e.printStackTrace();
  50. }
  51. }
  52. /**
  53. *发送消息的方法
  54. */
  55. public void send(String msg){
  56. try {
  57. PrintStream ps = new PrintStream(socket.getOutputStream());
  58. ps.println(msg);
  59. ps.flush();
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. /**
  65. *读取服务器传回的方法
  66. */
  67. public void recevie(){
  68. new Thread(){
  69. public void run(){
  70. while(true){
  71. try {
  72. InputStream is = socket.getInputStream();
  73. BufferedReader br = new BufferedReader(new InputStreamReader(is));
  74. String str = br.readLine();
  75. Message message = new Message();
  76. Bundle bundle = new Bundle();
  77. bundle.putString("msg", str);
  78. message.setData(bundle);
  79. handler.sendMessage(message);
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. }
  85. }.start();
  86. }
  87. }

二、RUL、URLConnection、httpURLConnection、ApacheHttp、WebView


    
  1. public class TestURLActivity extends Activity implements OnClickListener {
  2. private Button connectBtn;
  3. private Button urlConnectionBtn;
  4. private Button httpUrlConnectionBtn;
  5. private Button httpClientBtn;
  6. private ImageView showImageView;
  7. private TextView showTextView;
  8. private WebView webView;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.test_url_main);
  13. connectBtn = (Button) findViewById(R.id.test_url_main_btn_connect);
  14. urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
  15. httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
  16. httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
  17. showImageView = (ImageView) findViewById(R.id.test_url_main_iv_show);
  18. showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
  19. webView = (WebView) findViewById(R.id.test_url_main_wv);
  20. connectBtn.setOnClickListener(this);
  21. urlConnectionBtn.setOnClickListener(this);
  22. httpUrlConnectionBtn.setOnClickListener(this);
  23. httpClientBtn.setOnClickListener(this);
  24. }
  25. @Override
  26. public void onClick(View v) {
  27. // 直接使用URL对象进行连接
  28. if (v == connectBtn) {
  29. try {
  30. URL url = new URL("http://192.168.1.100:8080/myweb/image.jpg");
  31. InputStream is = url.openStream();
  32. Bitmap bitmap = BitmapFactory.decodeStream(is);
  33. showImageView.setImageBitmap(bitmap);
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. // 直接使用URLConnection对象进行连接
  39. if (v == urlConnectionBtn) {
  40. try {
  41. URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");
  42. URLConnection connection = url.openConnection();
  43. InputStream is = connection.getInputStream();
  44. byte[] bs = new byte[1024];
  45. int len = 0;
  46. StringBuffer sb = new StringBuffer();
  47. while ((len = is.read(bs)) != -1) {
  48. String str = new String(bs, 0, len);
  49. sb.append(str);
  50. }
  51. showTextView.setText(sb.toString());
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. // 直接使用HttpURLConnection对象进行连接
  57. if (v == httpUrlConnectionBtn) {
  58. try {
  59. URL url = new URL(
  60. "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
  61. HttpURLConnection connection = (HttpURLConnection) url
  62. .openConnection();
  63. connection.setRequestMethod("GET");
  64. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  65. String message = connection.getResponseMessage();
  66. showTextView.setText(message);
  67. }
  68. } catch (Exception e) {
  69. e.printStackTrace();
  70. }
  71. }
  72. // 使用ApacheHttp客户端进行连接(重要方法)
  73. if (v == httpClientBtn) {
  74. try {
  75. HttpClient client = new DefaultHttpClient();
  76. // 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
  77. // HttpGet httpGet = new
  78. // HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
  79. // post提交的方式
  80. HttpPost httpPost = new HttpPost(
  81. "http://192.168.1.100:8080/myweb/hello.jsp");
  82. // 如果是Post提交可以将参数封装到集合中传递
  83. List dataList = new ArrayList();
  84. dataList.add(new BasicNameValuePair("username", "aaaaa"));
  85. dataList.add(new BasicNameValuePair("pwd", "123"));
  86. // UrlEncodedFormEntity用于将集合转换为Entity对象
  87. httpPost.setEntity(new UrlEncodedFormEntity(dataList));
  88. // 获取相应消息
  89. HttpResponse httpResponse = client.execute(httpPost);
  90. // 获取消息内容
  91. HttpEntity entity = httpResponse.getEntity();
  92. // 把消息对象直接转换为字符串
  93. String content = EntityUtils.toString(entity);
  94. //showTextView.setText(content);
  95. //通过webview来解析网页
  96. webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
  97. //给点url来进行解析
  98. //webView.loadUrl(url);
  99. } catch (ClientProtocolException e) {
  100. e.printStackTrace();
  101. } catch (IOException e) {
  102. e.printStackTrace();
  103. }
  104. }
  105. }
  106. }

三、使用webService


   
  1. public class LoginActivity extends Activity implements OnClickListener{
  2. private Button loginBtn;
  3. private static final String SERVICE_URL = "http://192.168.1.100:8080/loginservice/LoginServicePort";
  4. private static final String NAMESPACE = "http://service.lovo.com/";
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.login_main);
  9. loginBtn = (Button) findViewById(R.id.login_main_btn_login);
  10. loginBtn.setOnClickListener(this);
  11. }
  12. @Override
  13. public void onClick(View v) {
  14. if(v == loginBtn){
  15. //创建WebService的连接对象
  16. HttpTransportSE httpSE = new HttpTransportSE(SERVICE_URL);
  17. //通过SOAP1.1协议对象得到envelop
  18. SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  19. //根据命名空间和方法名来创建SOAP对象
  20. SoapObject soapObject = new SoapObject(NAMESPACE, "validate");
  21. //向调用方法传递参数
  22. soapObject.addProperty("arg0", "abc");
  23. soapObject.addProperty("arg1","123");
  24. //将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息
  25. envelop.bodyOut = soapObject;
  26. try {
  27. //开始调用远程的方法
  28. httpSE.call(null, envelop);
  29. //得到远程方法返回的SOAP对象
  30. SoapObject resultObj = (SoapObject) envelop.bodyIn;
  31. //根据名为return的键来获取里面的值,这个值就是方法的返回值
  32. String returnStr = resultObj.getProperty("return").toString();
  33. Toast.makeText(this, "返回值:"+returnStr, Toast.LENGTH_LONG).show();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. } catch (XmlPullParserException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. }



文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/48139901

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。