前言,Android的网络通信的方式有两种:使用Socket或者HTTP,今天这一篇我们详细讲解使用HTTP实现的网络通信,HTTP又包括两种方式编程方式:

(1)HttpUrlConnection;

(2)HttpClient;

好了,我们直接进行讲解,当然之前也会有一部分有关Android网络通信的其他知识,我们也应该了解。

一.获取网络状态的方法

(1)MainActivity.java中的关键代码

1
2
3
4
5
6
7
8
//网络管理类,可以判断是否能上网,以及网络类型
            ConnectivityManager cm=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info=cm.getActiveNetworkInfo();
            if(info!=null){
                Toast.makeText(MainActivity.this"连网正常"+info.getTypeName(), Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(MainActivity.this"未连网", Toast.LENGTH_SHORT).show();
            }

(2)注意:一定要在主配置文件中增加这个权限

它是application的兄弟标签:

1 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

(3)OK,我们看一下我们的设备的上网状态和类型吧:

二.使用URL访问网页源码

(1)MainActivity.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.example.l0903_urldata;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
/**
 * 访问网页源码
 * @author asus
 *
 */
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            //访问百度的html文件的源码
            InputStream is=new URL("http://www.baidu.com").openStream();
            //读取数据的包装流
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            //str用于读取一行数据
            String str=null;
            //StringBuffer用于存储所欲数据
            StringBuffer sb=new StringBuffer();
            while((str=br.readLine())!=null){
                sb.append(str);
            }
            System.out.println(sb.toString());
        catch (MalformedURLException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(2)注意:有关网络的操作都需要在主配置文件里添加下面这个权限:

1 <uses-permission android:name="android.permission.INTERNET"/>

三.WebView 控件的简单使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.example.l0903_webview;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
/**
 * 就是一个浏览器控件
 * 其实没什么用
 * @author asus
 *
 */
public class MainActivity extends Activity {
    private WebView wv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv=(WebView) findViewById(R.id.webView1);
        //WebView控件的方法,loadUrl用于加载指定的网络地址
        wv.loadUrl("http://www.baidu.com");
    }
}

运行效果:

四.使用HttpUrlConnection的编写方式实现Android的网络通信

1.首先,自己先搭建一个服务器:

2.下面是客户端的事了:

(1)通过get方式:

MainActivity.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.example.l0903_httpurlcnectionget;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
/**
 * 通过Get方法获取服务器的数据
 * 直接在地址中用"?+键值+value"的方式来使用
 * 所以传递的参数直接显示出来,不安全
 * @author asus
 *
 */
public class MainActivity extends Activity {
    private HttpURLConnection conn;
    private URL url;
    private InputStream is;
    private TextView tv;
    private EditText et;
    private String name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView) findViewById(R.id.textView1);
        et=(EditText) findViewById(R.id.editText1);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
                                                                                                                                              
            @Override
            public void onClick(View v) {
                name=et.getText().toString();
                //定义访问的服务器地址,10.0.2.2是Android的访问的本地服务器地址
                String urlDate="http://10.0.2.2:8080/My_Service/webdate.jsp?name="+name;
                try {
                    //封装访问服务器的地址
                    url=new URL(urlDate);
                    try {
                        //打开对服务器的连接
                        conn=(HttpURLConnection) url.openConnection();
                        //连接服务器
                        conn.connect();
                        /**读入服务器数据的过程**/
                        //得到输入流
                        is=conn.getInputStream();
                        //创建包装流
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        //定义String类型用于储存单行数据
                        String line=null;
                        //创建StringBuffer对象用于存储所有数据
                        StringBuffer sb=new StringBuffer();
                        while((line=br.readLine())!=null){
                            sb.append(line);
                        }
                        //用TextView显示接收的服务器数据
                        tv.setText(sb.toString());
                        System.out.println(sb.toString());
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

权限(同上面第二个,所有与网络有关的操作都需要添加,下面的就不再赘述了)

运行效果:

(2)通过post方式(安全)

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.example.l0903_httpurlconectionpost;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
/**
 * 通过Post方法传递参数
 * 安全
 * @author asus
 *
 */
public class MainActivity extends Activity {
    private HttpURLConnection conn;
    private URL url;
    private InputStream is;
    private OutputStream os;
    private EditText et;
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et=(EditText) findViewById(R.id.editText1);
        tv=(TextView) findViewById(R.id.tv);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
                                                                                   
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String urlDate="http://10.0.2.2:8080/My_Service/webdate.jsp";
                try {
                    url=new URL(urlDate);
                    try {
                        //打开服务器
                        conn=(HttpURLConnection) url.openConnection();
                        //设置输入输出流
                        conn.setDoOutput(true);
                        conn.setDoInput(true);
                        //设置请求的方法为Post
                        conn.setRequestMethod("POST");
                        //Post方式不能缓存数据,则需要手动设置使用缓存的值为false
                        conn.setUseCaches(false);
                        //连接数据库
                        conn.connect();
                        /**写入参数**/
                        os=conn.getOutputStream();
                        //封装写给服务器的数据(这里是要传递的参数)
                        DataOutputStream dos=new DataOutputStream(os);
                        //写方法:name是key值不能变,编码方式使用UTF-8可以用中文
                        dos.writeBytes("name="+URLEncoder.encode(et.getText().toString(), "UTF-8"));
                        //关闭外包装流
                        dos.close();
                        /**读服务器数据**/
                        is=conn.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=null;
                        StringBuffer sb=new StringBuffer();
                        while((line=br.readLine())!=null){
                            sb.append(line);
                        }
                        tv.setText(sb.toString());
                        System.out.println(sb.toString());
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
                                                                           
    }
}

五.使用HttpClient的编写方式实现Android的网络通信

1.服务器同上;

2.使用get的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.l0903_http_get;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
    private HttpGet get;
    private HttpClient cliet;
    private HttpResponse response;
    private HttpEntity entity;
    private InputStream is;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        get=new HttpGet("http://10.0.2.2:8080/My_Service/webdate.jsp?name=ooooooo");
        cliet=new DefaultHttpClient();
        try {
            response=cliet.execute(get);
            entity=response.getEntity();
            is=entity.getContent();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String line=null;
            StringBuffer sb=new StringBuffer();
            while((line=br.readLine())!=null){
                sb.append(line);
            }
            System.out.println(sb.toString());
        catch (ClientProtocolException e) {
            e.printStackTrace();
        catch (IOException e) {
            e.printStackTrace();
        }
                                                
    }
}

3.使用post的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.example.l0903_http_post;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
    //创建请求对象
    private HttpPost post;
    //创建客户端对象
    private HttpClient cliet;
    //创建发送请求的对象
    private HttpResponse response;
    //
    private UrlEncodedFormEntity urlEntity;
    //创建接收返回数据的对象
    private HttpEntity entity;
    //创建流对象
    private InputStream is;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //包装请求的地址
        post=new HttpPost("http://10.0.2.2:8080/My_Service/webdate.jsp");
        //创建默认的客户端对象
        cliet=new DefaultHttpClient();
        //用list封装要向服务器端发送的参数
        List<BasicNameValuePair> pairs=new ArrayList<BasicNameValuePair>();
        pairs.add(new BasicNameValuePair("name""llllllllll"));
        try {
            //用UrlEncodedFormEntity来封装List对象
            urlEntity=new UrlEncodedFormEntity(pairs);
            //设置使用的Entity
            post.setEntity(urlEntity);
            try {
                //客户端开始向指定的网址发送请求
                response=cliet.execute(post);
                //获得请求的Entity
                entity=response.getEntity();
                is=entity.getContent();
                //下面是读取数据的过程
                BufferedReader br=new BufferedReader(new InputStreamReader(is));
                String line=null;
                StringBuffer sb=new StringBuffer();
                while((line=br.readLine())!=null){
                    sb.append(line);
                }
                System.out.println(sb.toString());
            catch (ClientProtocolException e) {
                e.printStackTrace();
            catch (IOException e) {
                e.printStackTrace();
            }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
                                             
                                             
    }
}

4.实现HttpClient通信与AsyncTask异步机制的结合:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.example.l0903_http_asynctask_get;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
/**
 *
 * @author asus
 *
 */
public class MainActivity extends Activity {
    private TextView tv;// 创建请求对象
    private HttpGet httpGet;
    // 创建客户端对象
    private HttpClient httpClient;
    // 发送请求的对象
    private HttpResponse httpResponse;
    // 接收返回数据
    private HttpEntity httpEntity;
    // 创建流
    private InputStream in;
    private ProgressDialog pd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
            @Override
            protected String doInString...  params) {
                String urlstr = params[0];
                httpGet = new HttpGet(urlstr);
                httpClient = new DefaultHttpClient();
                try {
                    // 向服务器端发送请求
                    httpResponse = httpClient.execute(httpGet);
                    httpEntity = httpResponse.getEntity();
                    in = httpEntity.getContent();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(in));
                    String line = null;
                    StringBuffer sb = new StringBuffer();
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    System.out.println(sb.toString());
                    return sb.toString();
                catch (ClientProtocolException e) {
                    e.printStackTrace();
                catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    tv.setText(result);
                    pd.dismiss();// 消除dialog
                }
                super.onPostExecute(result);
            }
        };
        pd = ProgressDialog.show(this"请稍后。。。""正在请求数据");
        asyncTask.execute("http://10.0.2.2:8080/My_Service/webdate.jsp?name=haha&age=hh");
    }
}

运行效果:

详细讲解Android的网络通信(HttpUrlConnection和HttpClient)的更多相关文章

  1. android中的HttpURLConnection和HttpClient实现app与pc数据交互

    自学android的这几天很辛苦,但是很满足,因为每当学到一点点知识点都会觉得很开心,觉得今天是特别有意义的,可能这个就是一种莫名的热爱吧. 下面来说说今天学习的HttpURLConnection和H ...

  2. 详细讲解Android对自己的应用代码进行混淆加密防止反编译

    1.查看项目中有没有proguard.cfg. 2.如果没有那就看看这个文件中写的什么吧,看完后将他复制到你的项目中. -optimizationpasses 5 -dontusemixedcasec ...

  3. 详细讲解Android中的Message的源码

    相信大家对于Android中的Handler是在为熟悉不过了,但是要知道,Handler就其本身而言只是一个壳子,真正在内部起到作用的是Message这个类,对于Message这个类,相信大家也不会陌 ...

  4. 详细讲解Android中的AbsListView的源码

    不知道各位童鞋们在开发的过程中有没有感兴趣过ListView是如何实现的呢?其实本身ListView的父类AbsListView才是关键,但是如果大家看过源码的话,会发现AbsListView将近70 ...

  5. Android訪问网络,使用HttpURLConnection还是HttpClient?

    原文地址:http://android-developers.blogspot.com/2011/09/androids-http-clients.html 大多数的Android应用程序都会使用HT ...

  6. Android入门(二十)HttpURLConnection与HttpClient

    原文链接:http://www.orlion.ga/679/ 在 Android上发送 HTTP请求的方式一般有两种,HttpURLConnection和 HttpClient. 一.HttpURLC ...

  7. Android HttpURLConnection And HttpClient

    Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...

  8. Android webservice的用法详细讲解

    Android webservice的用法详细讲解 看到有很多朋友对WebService还不是很了解,在此就详细的讲讲WebService,争取说得明白吧.此文章采用的项目是我毕业设计的webserv ...

  9. android 网络编程之HttpURLConnection与HttpClient使用与封装

    1.写在前面     大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议.     本文并 ...

随机推荐

  1. poj2299 Ultra-QuickSort(线段树求逆序对)

    Description In this problem, you have to analyze a particular sorting algorithm. The algorithm proce ...

  2. easyui datagrid deleteRow(删除行)的BUG

    有时候想临时保存一些数据,等确定好后在批量一次提交,但EasyUI  datagrid 用的时候添加可以正常,如果从中间删除那行号就全乱了.导致删除的时候有可能删除上一行数据. function ad ...

  3. C#7.0连接MySQL8.0数据库的小笔记

    1.要连接MySql数据库必须首先下载MySql官方的连接.net的文件,文件下载地址为https://dev.mysql.com/downloads/connector/net/6.6.html#d ...

  4. VS Code基本使用

    1. Activity Bar 1.1 Explorer 1.1.1. OPEN EDITORS 所有在右侧编辑区打开的文件列表 1.1.2 {PROJECTNAME} 某个文件夹下的文件树 1.2 ...

  5. NFS4 挂载同主机多个目录

    写在前面的话 事情是酱婶儿的,前两天实在是帮他们查日志查的心里交瘁了,而且有些时候下班了,也就不想再接到这样的需求,于是想基于 Nginx 做一个文件下载中心,在这个文件下载中心里面存有各个服务的日志 ...

  6. ubuntu14.04,安装Gnome 15.10 (桌面)

    Linux:ubuntu14.04 Gnome:15.10 更新最新版Gnome的一个好处:更新了ubuntu的软件源,我们可以使用ubuntu的软件中心获取更多需要的软件!! ubuntu默认的桌面 ...

  7. 如何设置linux支持上传的文件中文不乱吗

    一.背景: 1.由于客户的需求,需要a链接打开的pdf文件,支持中文名称的 二.步骤 ①.查看当前编码 locale ②.编辑 vi  /etc/profile 打开后结尾处添加  export LA ...

  8. 计算机基础知识和tcp详解

    计算机基础知识 作为应用软件开发程序员是写应用软件的,而应用软件必须应用在操作系统之上,调用操作系统接口,由操作系统控制硬件 比如客户端软件想要基于网络发送一条消息给服务端软件,流程是: 1.客户端软 ...

  9. 【spring boot】FilterRegistrationBean介绍

    前言 以往的javaee配置过滤器是在web.xml中配置的,如下代码 <filter> <filter-name>TestFilter</filter-name> ...

  10. Communication with each role instance in Azure

    Use WCF  Communication with role instance in azure 1)In worker role build WCF Service public overrid ...