在Android应用开发中,我们经常会与服务器交互,获取或上传数据,这就需要用到网络请求,一般情况下是使用HTTP协议去发送和接收网络数据,而HTTP又包括两种通信方式,即:HttpUrlConnection和HttpClient。
代码例子:https://git.oschina.net/ysx_xx/HttpText/tree/master
下面我简单地介绍这两种方式的使用:
首先,要进行网络请求,我们要先给应用添加网络权限,有两种方式添加:
1. 打开AndroidManifest.xml文件,选择permission,点击Add:
选择最后一个UsesPermission:
然后在右边Name选项找到android.permission.INTERNET,保存
然后再选择AndroidManifest.xml选项,就能看到
-------------------------------------------------------------------------------------------------------------------------------------------------------
好了,下面来讲讲那两种请求方式的使用
1. HttpUrlConnection:
先new一个URL对象并传入网络地址,再调用openConnection()方法获取HttpUrlConnection实例,然后设置HTTP请求的方法(GET/POST),接着设置连接超时、读取超时、消息头等,这个可以根据实际情况编写,之后用getInputStream()方法获取从服务器返回的输入流,并读取内容,最后调用disconnect()方法关闭。
代码:
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com/");
// 调用URL的openConnection()方法,得到HttpURLConnection的实例
connection = (HttpURLConnection) url.openConnection();
// 设置HTTP请求方法为GET,一般GET为从服务器获取数据,POST为提交数据给服务器
connection.setRequestMethod("GET");
// 设置连接超时的毫秒数
connection.setConnectTimeout(8000);
// 设置读取超时的毫秒数
connection.setReadTimeout(8000);
// 获取服务器返回的输入流
InputStream in = connection.getInputStream();
// 对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String response = "", line;
while ((line = reader.readLine()) != null) {
response += line;
}
//获取成功,发送成功信息
Message message = new Message();
message.what = SUCCESS;
message.obj = response;
mHandler.sendMessage(message);
} catch (Exception e) {
//发送失败信息
Message message = new Message();
message.what = FAILE;
message.obj = "请求失败";
mHandler.sendMessage(message);
e.printStackTrace();
} finally {
if (connection != null) {
//如果connection为null,则关闭它
connection.disconnect();
}
}
}
}).start();
运行效果如下:
以上是介绍GET方式,那如果要向服务器提交数据呢?
我们可以把请求方式改为POST,并提交参数
例如:connection.setRequestMethod(“POST”);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(“username=小熊&password=123456”);
2. 下面来看看HttpClient的用法:
HttpClient是一个接口,我们要先创建一个DefaultHttpClient的实例,再创建一个HttpGet对象并传入网络地址,然后调用HttpClient的execute()方法发送GET请求,最后调用HttpResponse的getStatusLine()的getStatusCode()方法获取服务器返回的状态码,如果为200则说明成功
代码:
new Thread(new Runnable() {
@Override
public void run() {
try {
//因为HttpClient是一个接口,所以用DefaultHttpClient()方法创建一个实例
HttpClient httpClient = new DefaultHttpClient();
//创建HttpGet对象并传入网络地址,并调用HttpClient的execute方法发送GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
//先取出服务器返回的状态码,如果是200则说明请求响应成功,这里可以自行判断获得的状态码
//是什么来判断是否成功或是什么失败
if(httpResponse.getStatusLine().getStatusCode() == 200){
//请求响应成功,调用getEntity()方法获取HttpEntity实例并转换成字符串
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
//获取成功,发送成功信息
Message message = new Message();
message.what = SUCCESS;
message.obj = response;
mHandler.sendMessage(message);
}
} catch (Exception e) {
//发送失败信息
Message message = new Message();
message.what = FAILE;
message.obj = "请求失败";
mHandler.sendMessage(message);
e.printStackTrace();
}
}
}).start();
运行效果跟HttpURLConnection一样,这里就不多发一遍了。下面是HttpClient的POST方式:
关键代码:
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List params = new ArrayList();
params.add(new BasicNameValuePair("username", "小熊"));
params.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
HttpURLConnectionText.java:
public class HttpURLConnectionText extends Activity implements OnClickListener {
private final static int SUCCESS = 1;
private final static int FAILE = 0;
private TextView result;
private Button send;
private LoadingDialog loadingDialog;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData() {
mContext = this;
result = (TextView) findViewById(R.id.result);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(this);
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
String response;
if(loadingDialog != null && loadingDialog.isShowing()){
loadingDialog.dismiss();
}
switch (msg.what) {
case SUCCESS:
response = msg.obj.toString();
result.setText(response);
break;
case FAILE:
response = msg.obj.toString();
result.setText(response);
break;
}
};
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send:
loadingDialog = new LoadingDialog(mContext);
loadingDialog.setCancel(false);
loadingDialog.show();
startSend();
break;
}
}
private void startSend() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com/");
// 调用URL的openConnection()方法,得到HttpURLConnection的实例
connection = (HttpURLConnection) url.openConnection();
// 设置HTTP请求方法为GET,一般GET为从服务器获取数据,POST为提交数据给服务器
connection.setRequestMethod("GET");
// 设置连接超时的毫秒数
connection.setConnectTimeout(8000);
// 设置读取超时的毫秒数
connection.setReadTimeout(8000);
// 获取服务器返回的输入流
InputStream in = connection.getInputStream();
// 对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String response = "", line;
while ((line = reader.readLine()) != null) {
response += line;
}
//获取成功,发送成功信息
Message message = new Message();
message.what = SUCCESS;
message.obj = response;
mHandler.sendMessage(message);
} catch (Exception e) {
//发送失败信息
Message message = new Message();
message.what = FAILE;
message.obj = "请求失败";
mHandler.sendMessage(message);
e.printStackTrace();
} finally {
if (connection != null) {
//如果connection为null,则关闭它
connection.disconnect();
}
}
}
}).start();
}
}
HttpClientText.java:
public class HttpClientText extends Activity implements OnClickListener {
private final static int SUCCESS = 1;
private final static int FAILE = 0;
private TextView result;
private Button send;
private LoadingDialog loadingDialog;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
}
private void initData() {
mContext = this;
result = (TextView) findViewById(R.id.result);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(this);
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
String response;
if(loadingDialog != null && loadingDialog.isShowing()){
loadingDialog.dismiss();
}
switch (msg.what) {
case SUCCESS:
response = msg.obj.toString();
result.setText(response);
break;
case FAILE:
response = msg.obj.toString();
result.setText(response);
break;
}
};
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send:
loadingDialog = new LoadingDialog(mContext);
loadingDialog.setCancel(false);
loadingDialog.show();
startSend();
break;
}
}
private void startSend() {
new Thread(new Runnable() {
@Override
public void run() {
try {
//因为HttpClient是一个接口,所以用DefaultHttpClient()方法创建一个实例
HttpClient httpClient = new DefaultHttpClient();
//创建HttpGet对象并传入网络地址,并调用HttpClient的execute方法发送GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
//先取出服务器返回的状态码,如果是200则说明请求响应成功,这里可以自行判断获得的状态码
//是什么来判断是否成功或是什么失败
if(httpResponse.getStatusLine().getStatusCode() == 200){
//请求响应成功,调用getEntity()方法获取HttpEntity实例并转换成字符串
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
//获取成功,发送成功信息
Message message = new Message();
message.what = SUCCESS;
message.obj = response;
mHandler.sendMessage(message);
}
} catch (Exception e) {
//发送失败信息
Message message = new Message();
message.what = FAILE;
message.obj = "请求失败";
mHandler.sendMessage(message);
e.printStackTrace();
}
}
}).start();
}
}