Android从网络下载资源有各种方式,可以用HttpClient,也可以用HttpUrlConnection。在这里,总结一下下载的各种方式,也方便今后的使用。
Android访问网络,使用HttpClient还是HttpUrlConnection?我们可以看博文http://blog.csdn.net/guolin_blog/article/details/12452307,该博文有详细介绍。
博文最后总结到:在Android 2.2版本之前,HttpClient拥有较少的bug,因此使用它是最好的选择。而在Android 2.3版本及以后,HttpURLConnection则是最佳的选择。它的API简单,体积较小,因而非常适用于Android项目。压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。对于新的应用程序应该更加偏向于使用HttpURLConnection。
1、HttpClient的请求方式
(1)Post方式,示例代码片段:参考博文:http://blog.csdn.net/lideguo1979/article/details/6966534,http://blog.csdn.net/zlfxy/article/details/8508176
使用Apache API:
①使用Map来存储参数
Map<String, String> map = new HashMap<String, String>();
map.put(“name”, “wusheng”);
map.put(“password”, “pwd”);
②使用DefaultHttpClient创建HttpClient实例
DefaultHttpClient httpClient = new DefaultHttpClient();
③构建HttpPost
HttpPost post = new HttpPost(“http://wu-sheng.iteye.com”);
④将由Map存储的参数转化为键值参数
List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(),
entry.getValue()));
}
⑤使用编码构建Post实体
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postData, HTTP.UTF_8);
⑥设置Post实体
post.setEntity(entity);
⑦执行Post方法
HttpResponse response = httpClient.execute(post);
⑧获取返回实体
HttpEntity httpEntity = response.getEntity();
⑨将H中返回实体转化为输入流
InputStream is = httpEntity.getContent();
⑩读取输入流,即返回文本内容
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = “”;
while((line=br.readLine())!=null){
sb.append(line);
}
- <span style="font-family:SimSun;font-size:14px;">private boolean loginServer(String username, String password)
- {
- boolean loginValidate = false;
- //使用apache HTTP客户端实现
- String urlStr = "http://10.0.2.2:8080/Login/Login";
- HttpPost request = new HttpPost(urlStr);
- //如果传递参数多的话,可以对传递的参数进行封装
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //添加用户名和密码
- params.add(new BasicNameValuePair("username",username));
- params.add(new BasicNameValuePair("password",password));
- try
- {
- //设置请求参数项
- request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- HttpClient client = getHttpClient();
- //执行请求返回相应
- HttpResponse response = client.execute(request);
- //判断是否请求成功
- if(response.getStatusLine().getStatusCode()==200)
- {
- loginValidate = true;
- //获得响应信息
- responseMsg = EntityUtils.toString(response.getEntity());
- }
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- return loginValidate;
- } </span>
- <span style="font-family:SimSun;font-size:14px;">//Http工具类
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.params.BasicHttpParams;
- import org.apache.http.params.HttpConnectionParams;
- import org.apache.http.params.HttpParams;
- import org.apache.http.util.EntityUtils;
- public class HttpUtil {
- public static String getHttpJSON(String url) {
- HttpGet httpRequest = new HttpGet(url);
- try {
- HttpClient httpclient = new DefaultHttpClient();
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- String jsonStr = EntityUtils.toString(httpResponse.getEntity(),
- "UTF-8");
- return jsonStr;
- }
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("==============e.printStackTrace() : "
- + e.getMessage());
- }
- return null;
- }
- public static int getHttpStatus() {
- int status = 0;
- HttpGet httpRequest = new HttpGet(
- "http://192.168.0.214/vote/AndroidConnServlet");
- try {
- HttpParams httpParameters = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
- HttpConnectionParams.setSoTimeout(httpParameters, 5000);
- HttpConnectionParams.setTcpNoDelay(httpParameters, true);
- HttpClient httpclient = new DefaultHttpClient(httpParameters);
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- status = httpResponse.getStatusLine().getStatusCode();
- } catch (Exception e) {
- e.printStackTrace();
- System.out
- .println("==============connection wifi fail,e.printStackTrace() : "
- + e.getMessage());
- }
- return status;
- }
- } </span>
(3)Get方式和Post方式,该博文介绍的也挺不错的:http://hi.baidu.com/kejisoft/item/9f63615201414617da1635a8
Get方式:
- <span style="font-family:SimSun;font-size:14px;">HttpClient mClient = new DefaultHttpClient();
- String targetUrl = "http://hi.baidu.com/kejisoft/pub/show/createtext";
- // 要请求的http地址
- HttpGet mHttpGet = new HttpGet(targetUrl);
- try {
- HttpResponse mResponse = mClient.execute(mHttpGet); // 执行get请求
- if(mResponse.getStasusLine().getStatusCode() == HttpStatus.SC_OK) {
- Log.d("请求OK!");
- Log.d(EntityUtils.toString(mResponse.getEntity()));
- }
- } catch(Exception e) {
- Log.d("异常了你要怎么去处理好?" + e);
- }
- </span>
Post方式:
- <span style="font-family:SimSun;font-size:14px;">HttpClient mClient = new DefaultHttpClient();
- String targetUrl = "http://hi.baidu.com/kejisoft/pub/show/createtext";
- // 要请求的http地址
- HttpGet mHttpGet = new HttpGet(targetUrl);
- try {
- HttpResponse mResponse = mClient.execute(mHttpGet); // 执行get请求
- if(mResponse.getStasusLine().getStatusCode() == HttpStatus.SC_OK) {
- Log.d("请求OK!");
- Log.d(EntityUtils.toString(mResponse.getEntity()));
- }
- } catch(Exception e) {
- Log.d("异常了你要怎么去处理好?" + e);
- }</span>
2、HttpUrlConnection的请求方式
示例代码:
- <span style="font-family:SimSun;font-size:14px;">String validateURL="http://10.0.2.2:8080/testhttp1/TestServlet?name=yang&pwd=123123";
- try {
- URL url = new URL(validateUrl); //创建URL对象
- //返回一个URLConnection对象,它表示到URL所引用的远程对象的连接
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5000); //设置连接超时为5秒
- conn.setRequestMethod("GET"); //设定请求方式
- conn.connect(); //建立到远程对象的实际连接
- //返回打开连接读取的输入流
- DataInputStream dis = new DataInputStream(conn.getInputStream());
- //判断是否正常响应数据
- if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
- System.out.println("网络错误异常!!!!");
- return false;
- }
- } catch (Exception e) {
- e.printStackTrace();
- System.out.println("这是异常!");
- } finally {
- if (conn != null) {
- conn.disconnect(); //中断连接
- }
- }</span>
3、从网络上下载
(1)网络下载,字节流转换为字符串
- <span style="font-family:SimSun;font-size:14px;">InputStream inputStream = url.openStream(); // 从URL上取得字节流
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int ch = -1;
- byte[] buffer = new byte[1024 * 4];
- while ((ch = inputStream.read(buffer)) != -1) {
- baos.write(buffer, 0, ch);
- }
- baos.flush();
- String responseXml = baos.toString(HTTP.UTF_8); // 依据需求可以选择要要的字符编码格式
- if (isr != null) { // 打印最后结果
- Log.i(TAG, "得到的字符串是:" + responseXml);
- }</span>
- <span style="font-family:SimSun;font-size:14px;">final int BUF_SIZE = 1024 * 8;
- byte[] buffer = new byte[BUF_SIZE];
- int bytes = is.read(buffer);
- if (bytes > 0) {
- int retVal = notify.urlDown(buffer, bytes);
- }
- FileOutputStream os = null;
- os = new FileOutputStream(downPath);
- final FileOutputStream oss = os;
- UrlNotify notify = new UrlNotify() {
- @Override
- public int urlDown(byte[] buffer, int bytes) {
- try {
- oss.write(buffer, 0, bytes);
- } catch (IOException e) {
- return ERROR_FILE_IO;
- }</span>
(2)字节流转换为字符流,写入文件代码Uitls示例:
- <span style="font-family:SimSun;font-size:14px;">package com.ijinshan.utils;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- /**
- * SD卡文件的写入,读取 文本工具类
- *
- * @author Gunpoder
- */
- public final class FileUtil {
- // 编码字符
- private static final String CONTENT_CHARSET = "UTF-8";
- /**
- * 写入或读取成功
- */
- public static final int FILE_WR_SUC = 0;
- /**
- * 文件未找到
- */
- public static final int FILE_WR_NOTFOUND = 1;
- /**
- * IO异常
- */
- public static final int FILE_WR_IOEXC = 2;
- /**
- * 往 SD卡中的指定文件中 一次写入数据
- *
- * @param desFilePath 文件全路径
- * @param content 写入内容
- * @param append 是否追加
- * @return FILE_WR_SUC 成功; FILE_WR_NOTFOUND 文件未找到; FILE_WR_IOEXC IO异常;
- * FILE_WR_NOTMOUNT Sd卡未挂载
- */
- public static int writeOnce(String desFilePath, String content,
- boolean append) {
- int res = FILE_WR_SUC;
- // 记录在隐藏文件夹中
- File desFile = new File(desFilePath);
- String strDir = desFile.getParent();
- File dir = new File(strDir);
- if (!dir.exists()) {
- dir.mkdirs();
- }
- BufferedWriter writer = null;
- try {
- writer = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(desFile, append), CONTENT_CHARSET));
- writer.write(content);
- } catch (FileNotFoundException e) {
- res = FILE_WR_NOTFOUND;
- e.printStackTrace();
- } catch (IOException e) {
- res = FILE_WR_IOEXC;
- e.printStackTrace();
- } finally {
- try {
- if (writer != null) {
- writer.close();
- writer = null;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return res;
- }
- }
- </span>
(3)从文件读取数据,代码片段:
- <span style="font-family:SimSun;font-size:14px;">public String readFile(String fromPath) {
- String number = null;
- StringBuffer sb = new StringBuffer();
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
- fromPath), "utf-8"));
- String line = null;
- while ((line = reader.readLine()) != null) {
- try {
- sb.append(line);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- reader.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sb.toString();
- }</span>