URLConnection的子类HttpURLConnection被广泛用于Android网络客户端编程,它与apache HttpClient是两种主要的客户端实现方式,google官方推荐使用HttpURLConnection.
URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。
URL请求的类别:
分为二类,GET与POST请求。二者的区别在于:
a. get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b. post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
这个案例就简单演示一下打开网页,以及下载图片
效果图:
获取网页:
public class HttpThreadPic extends Thread {
private String url;
private WebView myWebView;
private Handler myHandler;
@Override
public void run() {
try {
URL httpUrl=new URL(url);
try {
//创建一个HttpURLConnection对象或HttpsURLConnection对象
HttpURLConnection connection=(HttpURLConnection) httpUrl.openConnection();
//设置网络请求超时时间
connection.setReadTimeout(5000);
//设置请求方式
connection.setRequestMethod("GET");
final StringBuffer buffer=new StringBuffer();
//获取网页信息
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str;
//将信息存入缓冲区
while((str=reader.readLine())!=null){
buffer.append(str);
System.out.println(str);
}
//将网页信息加载到WebView;
myHandler.post(new Runnable() {
@Override
public void run() {
myWebView.loadData(buffer.toString(), "text/html;charset=utf-8", null);
}
});
} catch (IOException e) {
System.out.println("1");
e.printStackTrace();
}
} catch (MalformedURLException e) {
System.out.println("2");
e.printStackTrace();
}
}
//初始化
public HttpThreadPic(String url, WebView myWebView, Handler myHandler) {
super();
this.url = url;
this.myWebView = myWebView;
this.myHandler = myHandler;
}
}
下载图片:
public class HttpThread extends Thread {
private String url;
private ImageView myImageView;
private Handler myHandler;
private File picfile;
@Override
public void run() {
try {
URL httpUrl=new URL(url);
try {
//创建一个HttpURLConnection对象或HttpsURLConnection对象
HttpURLConnection connection=(HttpURLConnection) httpUrl.openConnection();
//设置网络请求超时时间
connection.setReadTimeout(5000);
//设置请求方式
connection.setRequestMethod("GET");
//设置是否从httpUrlConnection读入,默认情况下是true;
connection.setDoInput(true);
InputStream stream=connection.getInputStream();
FileOutputStream outputStream = null;
String filename=String.valueOf(System.currentTimeMillis());
//判断SD卡是否存在
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//获得SDK的一个目录
File parent=Environment.getExternalStorageDirectory();
picfile=new File(parent, filename);
outputStream=new FileOutputStream(picfile);
}
byte[] bs=new byte[2*1024];
int len;
if (outputStream!=null) {
while((len=stream.read(bs))!=-1){
outputStream.write(bs, 0, len);
}
}
final Bitmap bitmap=BitmapFactory.decodeFile(picfile.getAbsolutePath());
myHandler.post(new Runnable() {
@Override
public void run() {
myImageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
System.out.println("1");
e.printStackTrace();
}
} catch (MalformedURLException e) {
System.out.println("2");
e.printStackTrace();
}
}
public HttpThread(String url, ImageView myImageView, Handler myHandler) {
super();
this.url = url;
this.myImageView = myImageView;
this.myHandler = myHandler;
}
}
Activity的代码:
public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button bt_web, bt_pic;
private WebView myWebview;
private Handler handler = new Handler();
private ImageView myImageView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//传入网址
new HttpThreadPic("https://www.baidu.com/", myWebview, handler).start();
new HttpThread("http://img4.imgtn.bdimg.com/it/u=705115385,3322141037&fm=21&gp=0.jpg", myImageView, handler).start();
}
private void initView() {
myWebview = (WebView) findViewById(R.id.http_web);
myImageView = (ImageView) findViewById(R.id.http_image);
bt_pic = (Button) findViewById(R.id.http_bt_pic);
bt_web = (Button) findViewById(R.id.http_bt_web);
bt_pic.setOnClickListener(this);
bt_web.setOnClickListener(this);
}
//隐藏内容,显示内容
public void onClick(View v) {
switch (v.getId()) {
case R.id.http_bt_web:
myWebview.setVisibility(View.VISIBLE);
myImageView.setVisibility(View.GONE);
break;
case R.id.http_bt_pic:
myWebview.setVisibility(View.GONE);
myImageView.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
}