前言,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" );
}
} |
运行效果: