您的位置:首页 > 理论基础 > 计算机网络

Http些许己见

2015-11-14 18:21 483 查看
一,什么是Http协议:

超文本传输协议(Http-Hypertext-tranfer-protocal),定义了浏览器(即万维网客户端进程)怎样向万维网服务器请求万维网文档,以及服务器怎样

把文档传递给浏览器。从层次的角度来看,Http协议是应用层的协议,它是万维网上可靠的交换文件(文字,图片,音频等各种媒体文件)的基础。

二,http协议的工作流程:

1,客户端与服务端建立连接。

2,客户端向服务发送请求 ,请求格式:url(统一资源标示符,http(协议)://www.baidu.com(对应主机地址的域名)/search/error.html(接口))。

3,服务器收到请求后,给予相应的响应。

4,客户端接收到服务响应信息后,断开连接。

(一句话概括就是:客户端请求数据,服务端响应数据。也是个无状态的协议)

三,http协议的特点:

1,支持客户端/服务端模式

2,简单快捷:客户端向服务端请求服务时,只需要传送请求方法和路径。同时由于Http协议的简单,使得服务端的程序规模小,因而通讯速度很快。

3,灵活:Http协议允许传输任意类型的数据对象,正在传输的数据类型由Content-type标记

4,无连接:限制每次连接只处理一个请求。

5,无状态:Http协议是无状态协议。意味着后续请求需要前面的信息,它需要重传。

四,http1.1与Http1.0的区别:

http1.0时,每次连接断开后Tcp/Ip连接也会断开,Tcp/Ip连接不能复用,Http1.1则可以复用Tcp/Ip连接,减少了三次握手,提高效率。

Http1.1在Request里面增加了一个Host域。

Android中HttpURLConnection的应用。

加载一张图片:

package com.wang.demo_android;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;
import android.widget.ImageView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpThread extends Thread{

private WebView webView;
private ImageView imageView;

private Handler handler;
private String url;

public HttpThread(String url,WebView webView,Handler handler) {
this.url = url;
this.webView = webView;
this.handler = handler;
}

public HttpThread(String url,ImageView imageView,Handler handler){
this.url = url;
this.imageView = imageView;
this.handler = handler;
}

StringBuffer html =null;
@Override
public void run() {
LoadImg();
}

private void loadHtml(){
URL HttpUrl = null;
try {
HttpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) HttpUrl.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
html = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
while( (str=reader.readLine())!=null){
html.append(str);
}
handler.post(new Runnable() {

@Override
public void run() {
webView.loadData(html.toString(), "text/html;charset=utf-8", null);
Log.i("wangsongbin", "loadData");
}
});
} catch (Exception e) {
Log.i("wangsongbin", e.getMessage());
}

}

private void LoadImg(){
InputStream in = null;
FileOutputStream fos = null;
try {
URL imgUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
in = conn.getInputStream();
//判断SD卡是否挂载
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//拿到sd卡的根目录
File parent = new File(Environment.getExternalStorageDirectory().toString()+"/Alarms");
String fileName = url.substring(url.lastIndexOf("/")+1);
File file = new File(parent, fileName);
Log.i("wangsongbin", file.getAbsolutePath());
fos = new FileOutputStream(file);
byte[] buf =new byte[2*1024];
int len =0;
while((len = in.read(buf))!= -1){
fos.write(buf, 0, len);
};
String customUrl = Environment.getExternalStorageDirectory().toString()+"/Alarms/"+fileName;
final Bitmap bitmap = BitmapFactory.decodeFile(customUrl);
handler.post(new Runnable() {

@Override
public void run() {
imageView.setImageBitmap(bitmap);

}
});

}
} catch (Exception e) {
}finally{
try {
in.close();
fos.close();
} catch (Exception e) {

}
}

}

}


多线程下载图片:

package com.wang.demo_android.download;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ImageLoader {

private static String tag ="wangImgLoader";

private Executor threadPool = Executors.newFixedThreadPool(3);

private ImageView imageView;

private static final int MSG_OK = 1;

private String filePath;

private Handler handler = new Handler() {
int count = 0;

public void handleMessage(android.os.Message msg) {

switch (msg.what) {
case MSG_OK:
count++;
Log.i(tag, "count:"+count);
if (count == 3) {
Bitmap bm = BitmapFactory.decodeFile(filePath);
imageView.setImageBitmap(bm);
}
break;
}
};
};

public ImageLoader(ImageView imageView) {
this.imageView = imageView;
}

static class DownLoadImageRunnable implements Runnable {

private String url;

private long start;

private long end;

private String fileName;

private Handler handler;

public DownLoadImageRunnable(String url, long start, long end, String fileName,
Handler handler) {
this.url = url;
this.start = start;
this.end = end;
this.fileName = fileName;
this.handler = handler;
}

@Override
public void run() {
try {
URL httpURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
conn.setReadTimeout(5000);
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);// 这是分段请求的关键
conn.setRequestMethod("GET");
conn.setDoInput(true);
InputStream in = conn.getInputStream();
Log.i(tag, Environment.getExternalStorageState()+" ++ "+Environment.MEDIA_MOUNTED);
Log.i(tag, "sdcard is useful");
File file = new File(fileName);
RandomAccessFile out = new RandomAccessFile(file, "rwd");// 可读,可写,可操作
out.seek(start);
int len = 0;
byte[] buf = new byte[2 * 1024];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
Message msg = new Message();
msg.what = MSG_OK;
handler.sendMessage(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

private static String getFileName(String url) {
if (url != null) {
return url.substring(url.lastIndexOf("/") + 1);
}
return null;
}

/**
* 根据url加载一张图片
* @param url
*/
public void downLoadFile(String url) {
try {
URL httpURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
long count = conn.getContentLength();
long block = count / 3;
long start = 0;
long end = 0;
String fileName = getFileName(url);
File parent = Environment.getExternalStorageDirectory();
File file = new File(parent, fileName);
filePath = file.getAbsolutePath();
Log.i(tag, "filePath"+filePath);
for (int i = 0; i < 3; i++) {
start = i * block;
end = (i+1) * block;
if (i == 2) {
end = count;
}
DownLoadImageRunnable runnalbe = new DownLoadImageRunnable(url, start, end,
filePath, handler);
threadPool.execute(runnalbe);
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
上传图片:

package com.wang.demo_android.download;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.util.EntityUtils;

import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class UploadThread extends Thread {

private String url;

private String fileName;

private TextView tv_show;

private Handler handler;

public UploadThread(String url,String fileName,TextView tv_show,Handler handler) {
this.url = url;
this.fileName = fileName;
this.tv_show = tv_show;
this.handler = handler;
}

@Override
public void run() {
upLoad();
}

private void upLoad() {
String boundary = "---------------------------7df2e821c0374";
String prefix = "--";
String end = "\r\n";
// Content-Type
// multipart/form-data;boundary=---------------------------7df2e821c0374
// -----------------------------7df2e821c0374
// ---------------------------7df2e821c0374--
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(prefix + boundary + end);// 边界
out.writeBytes("Content-Disposition: form-data; "+
"name=\"file\"; filename=\""
+ "shamo.jpg" + "\""+end);
out.writeBytes("Content-Type: image/jpeg"+end+end);
//编写实体数据
FileInputStream fis =new FileInputStream(new File(fileName));
byte[] buf = new byte[4*1024];
int len = 0;
while((len=fis.read(buf))!=-1){
out.write(buf, 0, len);
}
out.writeBytes(end);
out.writeBytes(prefix+boundary+prefix+end);//这个与iE上监听的不符
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuffer sb = new StringBuffer();
String str = "";
while((str=in.readLine())!=null){
sb.append(str);
}
handler.post(new Runnable() {

@Override
public void run() {
tv_show.setText(sb.toString());
}
});
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
Log.i("wangFile", "has uploaded");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


Android中HttpClient的使用:

1,Google官方已经不再推荐使用HttpClient而推荐使用OkHttpClient,所以最新版本的SDK中已经删除了一些HttpClient的相关APi。

如果你仍然想要使用HttpClient,请下载jar(Http-4.3.6):下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: