Android网络编程之Http通信
Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是本人在学习中的总结与归纳。
1. HttpURLConnection接口
首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。
HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。创建方法如下代码所示:
1 |
URL url = new URL("http://www.51cto.com/index.jsp?par=123456");
|
2 |
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection(); |
通过以下方法可以对请求的属性进行一些设置,如下所示:
1 |
//设置输入和输出流 |
2 |
urlConn.setDoOutput(true);
|
3 |
urlConn.setDoInput(true);
|
4 |
//设置请求方式为POST |
5 |
urlConn.setRequestMethod("POST");
|
6 |
//POST请求不能使用缓存 |
7 |
urlConn.setUseCaches(false);
|
8 |
//关闭连接 |
9 |
urlConn.disConnection(); |
HttpURLConnection默认使用GET方式,例如下面代码所示:
01 |
//使用HttpURLConnection打开连接 |
02 |
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
|
03 |
//得到读取的内容(流)
|
04 |
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
|
05 |
// 为输出创建BufferedReader
|
06 |
BufferedReader buffer = new BufferedReader(in);
|
07 |
String inputLine = null;
|
08 |
//使用循环来读取获得的数据
|
09 |
while (((inputLine = buffer.readLine()) != null))
|
10 |
{
|
11 |
//我们在每一行后面加上一个"\n"来换行
|
12 |
resultData += inputLine + "\n";
|
13 |
}
|
14 |
//关闭InputStreamReader
|
15 |
in.close();
|
16 |
//关闭http连接
|
17 |
urlConn.disconnect();
|
如果需要使用POST方式,则需要setRequestMethod设置。代码如下:
01 |
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
|
02 |
//获得的数据
|
03 |
String resultData = "";
|
04 |
URL url = null;
|
05 |
try
|
06 |
{
|
07 |
//构造一个URL对象
|
08 |
url = new URL(httpUrl);
|
09 |
}
|
10 |
catch (MalformedURLException e)
|
11 |
{
|
12 |
Log.e(DEBUG_TAG, "MalformedURLException");
|
13 |
}
|
14 |
if (url != null)
|
15 |
{
|
16 |
try
|
17 |
{
|
18 |
// 使用HttpURLConnection打开连接
|
19 |
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
|
20 |
//因为这个是post请求,设立需要设置为true
|
21 |
urlConn.setDoOutput(true);
|
22 |
urlConn.setDoInput(true);
|
23 |
// 设置以POST方式
|
24 |
urlConn.setRequestMethod("POST");
|
25 |
// Post 请求不能使用缓存
|
26 |
urlConn.setUseCaches(false);
|
27 |
urlConn.setInstanceFollowRedirects(true);
|
28 |
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
|
29 |
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
|
30 |
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
|
31 |
// 要注意的是connection.getOutputStream会隐含的进行connect。
|
32 |
urlConn.connect();
|
33 |
//DataOutputStream流
|
34 |
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
|
35 |
//要上传的参数
|
36 |
String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
|
37 |
//将要上传的内容写入流中
|
38 |
out.writeBytes(content);
|
39 |
//刷新、关闭
|
40 |
out.flush();
|
41 |
out.close();
|
2. HttpClient接口
使用Apache提供的HttpClient接口同样可以进行HTTP操作。
对于GET和POST请求方法的操作有所不同。GET方法的操作代码示例如下:
01 |
// http地址 |
02 |
String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
|
03 |
//HttpGet连接对象
|
04 |
HttpGet httpRequest = new HttpGet(httpUrl);
|
05 |
//取得HttpClient对象
|
06 |
HttpClient httpclient = new DefaultHttpClient();
|
07 |
//请求HttpClient,取得HttpResponse
|
08 |
HttpResponse httpResponse = httpclient.execute(httpRequest);
|
09 |
//请求成功
|
10 |
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
|
11 |
{
|
12 |
//取得返回的字符串
|
13 |
String strResult = EntityUtils.toString(httpResponse.getEntity());
|
14 |
mTextView.setText(strResult);
|
15 |
}
|
16 |
else
|
17 |
{
|
18 |
mTextView.setText("请求错误!");
|
19 |
}
|
20 |
}
|
使用POST方法进行参数传递时,需要使用NameValuePair来保存要传递的参数。,另外,还需要设置所使用的字符集。代码如下所示:
01 |
// http地址 |
02 |
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
|
03 |
//HttpPost连接对象
|
04 |
HttpPost httpRequest = new HttpPost(httpUrl);
|
05 |
//使用NameValuePair来保存要传递的Post参数
|
06 |
List<NameValuePair> params = new ArrayList<NameValuePair>();
|
07 |
//添加要传递的参数
|
08 |
params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
|
09 |
//设置字符集
|
10 |
HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
|
11 |
//请求httpRequest
|
12 |
httpRequest.setEntity(httpentity);
|
13 |
//取得默认的HttpClient
|
14 |
HttpClient httpclient = new DefaultHttpClient();
|
15 |
//取得HttpResponse
|
16 |
HttpResponse httpResponse = httpclient.execute(httpRequest);
|
17 |
//HttpStatus.SC_OK表示连接成功
|
18 |
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
|
19 |
{
|
20 |
//取得返回的字符串
|
21 |
String strResult = EntityUtils.toString(httpResponse.getEntity());
|
22 |
mTextView.setText(strResult);
|
23 |
}
|
24 |
else
|
25 |
{
|
26 |
mTextView.setText("请求错误!");
|
27 |
}
|
28 |
}
|
HttpClient实际上是对Java提供方法的一些封装,在HttpURLConnection中的输入输出流操作,在这个接口中被统一封装成了HttpPost(HttpGet)和HttpResponse,这样,就减少了操作的繁琐性。
另外,在使用POST方式进行传输时,需要进行字符编码