使用httpclitet提交数据
HttpClient 是apache 开源组织研发的一个API,被Android 引入使用
- 案例
代码
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// [1]找到我们关心的控件
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
// 点击按钮 进行get方式提交数据
public void click1(View v) {
new Thread(){public void run() {
try {
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
//[2.1]定义get方式要提交的路径 小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码
String path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
//[3]获取httpclient实例
DefaultHttpClient client = new DefaultHttpClient();
//[3.1]准备get请求 定义 一个httpget实现
HttpGet get = new HttpGet(path);
//[3.2]执行一个get请求
HttpResponse response = client.execute(get);
//[4]获取服务器返回的状态码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//[5]获取服务器返回的数据 以流的形式返回
InputStream inputStream = response.getEntity().getContent();
//[6]把流转换成字符串
String content = StreamTools.readStream(inputStream);
//[7]展示结果
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
};}.start();
}
// [1]点击按钮 进行post方式提交数据
public void click2(View v) {
new Thread(){public void run() {
try {
//[2]获取用户名和密码
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
String path = "http://192.168.11.73:8080/login/LoginServlet";
//[3]以httpClient 方式进行post 提交
DefaultHttpClient client = new DefaultHttpClient();
//[3.1]准备post 请求
HttpPost post = new HttpPost(path);
//[3.1.0]准备parameters
List<NameValuePair> lists = new ArrayList<NameValuePair>();
//[3.1.1]准备 NameValuePair 实际上就是我们要提交的用户名 和密码 key是服务器key :username
BasicNameValuePair nameValuePair = new BasicNameValuePair("username",name);
BasicNameValuePair pwdValuePair = new BasicNameValuePair("password",pwd);
//[3.1.3] 把nameValuePair 和 pwdValuePair 加入到集合中
lists.add(nameValuePair);
lists.add(pwdValuePair);
//[3.1.3]准备entity
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(lists);
//[3.2]准备post方式提交的正文 以实体形式准备 (键值对形式 )
post.setEntity(entity);
HttpResponse response = client.execute(post);
//[4]获取服务器返回的状态码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//[5]获取服务器返回的数据 以流的形式返回
InputStream inputStream = response.getEntity().getContent();
//[6]把流转换成字符串
String content = StreamTools.readStream(inputStream);
//[7]展示结果
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
};}.start();
}
//封装toast方法 该toast方法执行在主线程
public void showToast(final String content){
runOnUiThread(new Runnable() {
@Override
public void run() {
//该方法一定是执行主线程
Toast.makeText(getApplicationContext(), content, 1).show();
}
});
}
}
使用Aynchttpclient提交数据
AsyncHttpClient 是一个Android 的异步HTTP 函数库,
使用此开源项目访问网络时,无需开启子线程,
因为调用其方法时传递的接口参数中的方法就是执行在主线程中的
- 案例 get/post请求
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// [1]找到我们关心的控件
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
// 点击按钮 进行get方式提交数据
public void click1(View v) {
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
//[2.1]定义get方式要提交的路径 小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码
try {
path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//[3]使用开源项目进行get请求
//[3.1]创建asynchttpclient
AsyncHttpClient client = new AsyncHttpClient();
//[3.2]进行get 请求
client.get(path, new AsyncHttpResponseHandler() {
//请求成功的回调方法
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
Toast.makeText(getApplicationContext(), new String(responseBody,"gbk"), 1).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//请求失败
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}
// [1]点击按钮 进行post方式提交数据
public void click2(View v) {
//[2]获取用户名和密码
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
String path = "http://192.168.11.73:8080/login/LoginServlet";
//[3.1]创建asynchttpclient
AsyncHttpClient client = new AsyncHttpClient();
//[3.1.0]准备请求体的内容
RequestParams params = new RequestParams();
params.put("username", name);
params.put("password", pwd);
//[3.2]进行post请求 params 请求的参数封装
client.post(path, params, new AsyncHttpResponseHandler() {
//请求成功 登录成功
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
Toast.makeText(getApplicationContext(), new String(responseBody,"gbk"), 1).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}
}
- 案例 上传
public void doUpload(View v) throws Exception {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
File path = Environment.getExternalStorageDirectory();
// 要想实现文件上传,直接在请求参数中添加file 对象即可
params.put("file", new File(path, "users.xml"));
// 然后通过post 方式发送请求
client.post("http://192.168.1.42:8080/MyDay15/uploadServlet", params,
new AsyncHttpResponseHandler() {
public void onSuccess(String content) {
Toast.makeText(getApplicationContext(), "上传成功!",
Toast.LENGTH_SHORT).show();
}
public void onFailure(Throwable error, String content) {
Toast.makeText(getApplicationContext(), "上传失败!",
Toast.LENGTH_SHORT).show();
}
});
}
多线程下载
在下载的时候多个线程并发可以占用服务器端更多资源,从而加快下载速度
原理
线程下载位置切分计算公式
断点续传
手机端下载数据时难免会出现无信号断线、电量不足等情况,所以需要断
点续传功能
- 案例 多线程下载及断点续传
public class MainActivity extends Activity {
private EditText et_path;
private EditText et_threadCount;
private LinearLayout ll_pb_layout;
private String path;
private static int runningThread; //代表当前正在运行的线程
private int threadCount;
private List<ProgressBar> pbLists; //用来存进度条的引用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// [1]找到我们关心的控件
et_path = (EditText) findViewById(R.id.et_path);
et_threadCount = (EditText) findViewById(R.id.et_threadCount);
ll_pb_layout = (LinearLayout) findViewById(R.id.ll_pb);
//[2]添加一个集合 用来存进度条的引用
pbLists = new ArrayList<ProgressBar>();
}
//点击按钮实现下载的逻辑
public void click(View v){
//[2]获取下载的路径
path = et_path.getText().toString().trim();
//[3]获取线程的数量
String threadCountt = et_threadCount.getText().toString().trim();
//[3.0]先移除进度条 在添加
ll_pb_layout.removeAllViews();
threadCount = Integer.parseInt(threadCountt);
pbLists.clear();
for (int i = 0; i < threadCount; i++) {
//[3.1]把我定义的item布局转换成一个view对象
ProgressBar pbView = (ProgressBar) View.inflate(getApplicationContext(), R.layout.item, null);
//[3.2]把pbView 添加到集合中
pbLists.add(pbView);
//[4]动态的添加进度条
ll_pb_layout.addView(pbView);
}
//[5]开始移植 联网 获取文件长度
new Thread(){public void run() {
//[一 ☆☆☆☆]获取服务器文件的大小 要计算每个线程下载的开始位置和结束位置
try {
//(1) 创建一个url对象 参数就是网址
URL url = new URL(path);
//(2)获取HttpURLConnection 链接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//(3)设置参数 发送get请求
conn.setRequestMethod("GET"); //默认请求 就是get 要大写
//(4)设置链接网络的超时时间
conn.setConnectTimeout(5000);
//(5)获取服务器返回的状态码
int code = conn.getResponseCode(); //200 代表获取服务器资源全部成功 206请求部分资源
if (code == 200) {
//(6)获取服务器文件的大小
int length = conn.getContentLength();
//[6.1]把 线程的数量赋值给正在运行的线程
runningThread = threadCount;
System.out.println("length:"+length);
//[二☆☆☆☆ ] 创建一个大小和服务器一模一样的文件 目的提前把空间申请出来
RandomAccessFile rafAccessFile = new RandomAccessFile(getFilename(path), "rw");
rafAccessFile.setLength(length);
//(7)算出每个线程下载的大小
int blockSize = length /threadCount;
//[三☆☆☆☆ 计算每个线程下载的开始位置和结束位置 ]
for (int i = 0; i < threadCount; i++) {
int startIndex = i * blockSize; //每个线程下载的开始位置
int endIndex = (i+1)*blockSize - 1;
//特殊情况 就是最后一个线程
if (i == threadCount - 1) {
//说明是最后一个线程
endIndex = length - 1;
}
System.out.println("线程id:::"+i + "理论下载的位置"+":"+startIndex+"-----"+endIndex);
//四 开启线程去服务器下载文件
DownLoadThread downLoadThread = new DownLoadThread(startIndex, endIndex, i);
downLoadThread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
};}.start();
}
//定义线程去服务器下载文件
private class DownLoadThread extends Thread{
//通过构造方法把每个线程下载的开始位置和结束位置传递进来
private int startIndex;
private int endIndex;
private int threadId;
private int PbMaxSize; //代表当前线程下载的最大值
//如果中断过 获取上次下载的位置
private int pblastPostion;
public DownLoadThread(int startIndex,int endIndex,int threadId){
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
//四 实现去服务器下载文件的逻辑
try {
//(0)计算当前进度条的最大值
PbMaxSize = endIndex - startIndex;
//(1) 创建一个url对象 参数就是网址
URL url = new URL(path);
//(2)获取HttpURLConnection 链接对象
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
//(3)设置参数 发送get请求
conn.setRequestMethod("GET"); //默认请求 就是get 要大写
//(4)设置链接网络的超时时间
conn.setConnectTimeout(5000);
//[4.0]如果中间断过 继续上次的位置 继续下载 从文件中读取上次下载的位置
File file =new File(getFilename(path)+threadId+".txt");
if (file.exists() && file.length()>0) {
FileInputStream fis = new FileInputStream(file);
BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
String lastPositionn = bufr.readLine(); //读取出来的内容就是上一次下载的位置
int lastPosition = Integer.parseInt(lastPositionn);
//[4.0]给我们定义的进度条条位置 赋值
pblastPostion = lastPosition - startIndex;
//[4.0.1]要改变一下 startIndex 位置
startIndex = lastPosition + 1;
System.out.println("线程id::"+threadId + "真实下载的位置"+":"+startIndex+"-----"+endIndex);
fis.close(); //关闭流
}
//[4.1]设置一个请求头Range (作用告诉服务器每个线程下载的开始位置和结束位置)
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
//(5)获取服务器返回的状态码
int code = conn.getResponseCode(); //200 代表获取服务器资源全部成功 206请求部分资源 成功
if (code == 206) {
//[6]创建随机读写文件对象
RandomAccessFile raf = new RandomAccessFile(getFilename(path), "rw");
//[6]每个线程要从自己的位置开始写
raf.seek(startIndex);
InputStream in = conn.getInputStream(); //存的是feiq.exe
//[7]把数据写到文件中
int len = -1;
byte[] buffer = new byte[1024*1024];//1Mb
int total = 0; //代表当前线程下载的大小
while((len = in.read(buffer))!=-1){
raf.write(buffer, 0, len);
total +=len;
//[8]实现断点续传 就是把当前线程下载的位置 给存起来 下次再下载的时候 就是按照上次下载的位置继续下载 就可以了
int currentThreadPosition = startIndex + total; //比如就存到一个普通的.txt文本中
//[9]用来存当前线程下载的位置
RandomAccessFile raff = new RandomAccessFile(getFilename(path)+threadId+".txt", "rwd");
raff.write(String.valueOf(currentThreadPosition).getBytes());
raff.close();
//[10]设置一下当前进度条的最大值 和 当前进度
pbLists.get(threadId).setMax(PbMaxSize);//设置进度条的最大值
pbLists.get(threadId).setProgress(pblastPostion+total);//设置当前进度条的当前进度
}
raf.close();//关闭流 释放资源
System.out.println("线程id:"+threadId + "---下载完毕了");
//[10]把.txt文件删除 每个线程具体什么时候下载完毕了 我们不知道
synchronized (DownLoadThread.class) {
runningThread--;
if (runningThread == 0) {
//说明所有的线程都执行完毕了 就把.txt文件删除
for (int i = 0; i < threadCount; i++) {
File delteFile = new File(getFilename(path)+i+".txt");
delteFile.delete();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//获取文件的名字 "http://192.168.11.73:8080/feiq.exe";
public String getFilename(String path){
int start = path.lastIndexOf("/")+1;
String substring = path.substring(start);
String fileName = Environment.getExternalStorageDirectory().getPath()+"/"+substring;
return fileName;
}
}
xutils使用
xutils已经实现了多线程下载断点续传
- 案例
public class MainActivity extends Activity {
private EditText et_path;
private ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//[0]获取我们关心的控件
et_path = (EditText) findViewById(R.id.et_path);
pb = (ProgressBar) findViewById(R.id.progressBar1);
}
//点击按钮实现断点续传下载逻辑
public void click(View v){
//[1]获取下载路径
String path = et_path.getText().toString().trim();
//[2]创建httputils对象
HttpUtils http = new HttpUtils();
//[3]实现断点下载 target下载文件的路径 autoResume 是否支持断点续传的逻辑
http.download(path, "/mnt/sdcard/xpg.mp3", true, new RequestCallBack<File>() {
//下载成功
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
Toast.makeText(getApplicationContext(), "下载成功", 1).show();
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
//total 代表总进度 current 代表当前进度
pb.setMax((int) total);
pb.setProgress((int) current);
}
//下载失败的回调
@Override
public void onFailure(HttpException error, String msg) {
}
});
}
}