安卓网络编程主要分三种方式:
* Socket 应用基本不用。
* HttpURLConnection 比较常用的网络编程方式。
* HttpClient 在2.3之前推荐使用,2.3之后被HttpURLConnection所代替。
开源项目:网络图片查看器android-smart-image-view-master。
//1.确定网址
String path = "http://192.168.13.13:8080/dd.jpg";
//2.找到智能图片查看器对象
SmartImageView siv = (SmartImageView) findViewById(R.id.iv);
//3.下载并显示图片
siv.setImageUrl(path);
GET:
Thread t = new Thread(){
@Override
public void run() {
//提交的数据需要经过url编码,英文和数字编码后不变
String path = "http://192.168.13.13/Web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
try {
URL url = new URL(path);
//获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//先建立连接,然后获取响应码
if(conn.getResponseCode() == 200){
//拿到服务器返回的输入流,流里的数据就是html的源文件
InputStream is = conn.getInputStream();
//从流里把文本数据取出来
String text = Utils.getTextFromStream(is);
//发送消息,让主线程刷新ui,显示源文件
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
post方式提交数据。
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run() {
//提交的数据需要经过url编码,英文和数字编码后不变
@SuppressWarnings("deprecation")
String path = "http://192.168.13.13/Web2/servlet/LoginServlet";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//拼接出要提交的数据的字符串
String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
//添加post请求的两行属性
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
//设置打开输出流
conn.setDoOutput(true);
//拿到输出流
OutputStream os = conn.getOutputStream();
//使用输出流往服务器提交数据
os.write(data.getBytes());
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
String text = Utils.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
get方式提交数据。
public void get(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run() {
String path = "http://192.168.13.13/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
//使用httpClient框架做get方式提交
//1.创建HttpClient对象
HttpClient hc = new DefaultHttpClient();
//2.创建httpGet对象,构造方法的参数就是网址
HttpGet hg = new HttpGet(path);
//3.使用客户端对象,把get请求对象发送出去
try {
HttpResponse hr = hc.execute(hg);
//拿到响应头中的状态行
StatusLine sl = hr.getStatusLine();
if(sl.getStatusCode() == 200){
//拿到响应头的实体
HttpEntity he = hr.getEntity();
//拿到实体中的内容,其实就是服务器返回的输入流
InputStream is = he.getContent();
String text = Utils.getTextFromStream(is);
//发送消息,让主线程刷新ui显示text
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
post方式提交。
public void post(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run() {
String path = "http://192.168.13.13/Web/servlet/CheckLogin";
//1.创建客户端对象
HttpClient hc = new DefaultHttpClient();
//2.创建post请求对象
HttpPost hp = new HttpPost(path);
//封装form表单提交的数据
BasicNameValuePair bnvp = new BasicNameValuePair("name", name);
BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);
List parameters = new ArrayList();
//把BasicNameValuePair放入集合中
parameters.add(bnvp);
parameters.add(bnvp2);
try {
//要提交的数据都已经在集合中了,把集合传给实体对象
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//设置post请求对象的实体,其实就是把要提交的数据封装至post请求的输出流中
hp.setEntity(entity);
//3.使用客户端发送post请求
HttpResponse hr = hc.execute(hp);
if(hr.getStatusLine().getStatusCode() == 200){
InputStream is = hr.getEntity().getContent();
String text = Utils.getTextFromStream(is);
//发送消息,让主线程刷新ui显示text
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
##多线程断点下载
原理:服务器CPU分配给每条线程的时间片相同,服务器带宽平均分配给每条线程,所以客户端开启的线程越多,就能抢占到更多的服务器资源
发送http请求至下载地址
String path = "http://192.168.1.102:8080/editplus.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
获取文件总长度,然后创建长度一致的临时文件
if(conn.getResponseCode() == 200){
//获得服务器流中数据的长度
int length = conn.getContentLength();
//创建一个临时文件存储下载的数据
RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rwd");
//设置临时文件的大小
raf.setLength(length);
raf.close();
确定线程下载多少数据
//计算每个线程下载多少数据
int blockSize = length / THREAD_COUNT;
for(int id = 1; id <= 3; id++){
//计算每个线程下载数据的开始位置和结束位置
int startIndex = (id - 1) * blockSize;
int endIndex = id * blockSize - 1;
if(id == THREAD_COUNT){
endIndex = length;
}
//开启线程,按照计算出来的开始结束位置开始下载数据
new DownLoadThread(startIndex, endIndex, id).start();
}
String path = "http://192.168.1.102:8080/editplus.exe";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//向服务器请求部分数据,"bytes="不要有空格,不然会出错。
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
conn.connect();
下载请求到的数据,存放至临时文件中
if(conn.getResponseCode() == 206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rwd");
//指定从哪个位置开始存放数据
raf.seek(startIndex);
byte[] b = new byte[1024];
int len;
while((len = is.read(b)) != -1){
raf.write(b, 0, len);
}
raf.close();
}
定义一个int变量记录每条线程下载的数据总长度,然后加上该线程的下载开始位置,得到的结果就是下次下载时,该线程的开始位置,把得到的结果存入缓存文件
//用来记录当前线程总的下载长度
int total = 0;
while((len = is.read(b)) != -1){
raf.write(b, 0, len);
total += len;
//每次下载都把新的下载位置写入缓存文本文件
RandomAccessFile raf2 = new RandomAccessFile(threadId + ".txt", "rwd");
raf2.write((startIndex + total + "").getBytes());
raf2.close();
}
下次下载开始时,先读取缓存文件中的值,得到的值就是该线程新的开始位置
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
int newStartIndex = Integer.parseInt(text);
//把读到的值作为新的开始位置
startIndex = newStartIndex;
fis.close();
三条线程都下载完毕之后,删除缓存文件
RUNNING_THREAD--;
if(RUNNING_THREAD == 0){
for(int i = 0; i <= 3; i++){
File f = new File(i + ".txt");
f.delete();
}
}
拿到下载文件总长度时,设置进度条的最大值
//设置进度条的最大值
pb.setMax(length);
进度条需要显示三条线程的整体下载进度,所以三条线程每下载一次,就要把新下载的长度加入进度条
定义一个int全局变量,记录三条线程的总下载长度
int progress;
刷新进度条
while((len = is.read(b)) != -1){
raf.write(b, 0, len);
//把当前线程本次下载的长度加到进度条里
progress += len;
pb.setProgress(progress);
每次断点下载时,从新的开始位置开始下载,进度条也要从新的位置开始显示,在读取缓存文件获取新的下载开始位置时,也要处理进度条进度
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
int newStartIndex = Integer.parseInt(text);
//新开始位置减去原本的开始位置,得到已经下载的数据长度
int alreadyDownload = newStartIndex - startIndex;
//把已经下载的长度设置入进度条
progress += alreadyDownload;
tv.setText(progress * 100 / pb.getMax() + "%");