HttpURLConnection继承了URLConnection,是一个轻量级的网络请求,是抽象类,无法直接实例化对象。
首先介绍他的使用方法:
1、建立url对象:
URL url = new URL();
2、获取URL实例:
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
3、设置获取方法:
huc.RequestMethod("GET");或者POST
4、设置响应时间:
huc.setConnectionTimeout(101000);huc.setReadTimeout(101000);
5、返回输入流,然后读取:
InputStream in = huc.getInputStream();
6、关闭网络请求:
huc.disconnect();
注意:这个小例子 要明白几个知识点:
1、因为是请求网上的图片加载,所以耗时间,因此要放在子线程中。
2、子线程不能更新UI,所以要用handler来更新UI;
3、handler的用法:
创建一个handler对象
private Handler handler = new Handler();
重写handlerMessage方法
public void handlerMessage(android.os.Message msg){
}
在子线程中创建Message对象,将数据绑定个msg。
Message msg = new Message();
msg.obj = result;
子线程的message对象msg将在子线程中使用senMessage()发个主线程的handler
handler.senMessage(msg);
主线程的handlermessage的方法接受子线程的数据,就可以更新UI了;
先看一下效果图:
第一步还是先看主xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edit"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查看图片"
android:id="@+id/button"/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</LinearLayout>
<ScrollView>这个是滚动条,就是如果图片很大就可以滚动着看(有点表达不清楚);
接着看主activity:
现在我比较喜欢在代码上注释,因为这样可以更清晰,而且自己也会在理一遍思路(毕竟是初学者):
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//我们设置点击事件,所以要继承OnClickListener接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//初始化对象
private EditText editText;
private ImageView imageView;
private Context mContext;//这个Context很强大,代表着...,总之写这个会让后面的代码简洁一点
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
//通过ID找到xml的控件
editText = (EditText) findViewById(R.id.edit);
Button button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.image);
//为bottom注册点击监听
button.setOnClickListener(this);
}
//这个是handler的步骤
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg){
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
};
};
@SuppressLint("WrongConstant")
@Override
public void onClick(View v) {
try{
//得到EditText的里面的内容
final String url = editText.getText().toString().trim();
//判断URL填写的是否为空
if(TextUtils.isEmpty(url)){
Toast.makeText(mContext,"url不能为空",0).show();
return;
}
//创建一个子线程,重写run方法
new Thread(new Runnable() {
@Override
public void run() {
try {
//这个是网络请求,把它放在子线程里
URL url1 = new URL(url);
HttpURLConnection connection=(HttpURLConnection)url1.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(1000*10);
//获取请求数据响应码
int code = connection.getResponseCode();
//如果code==200代表请求成功
if(code == 200){
//获取输入流,并转换成String
InputStream inputStream = connection.getInputStream();
//把输入流转化成图片
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}catch (Exception e){
e.printStackTrace();
}
}
}
创建一个获取文件的流并转换成String的工具类
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamUtils {
public static String streamToString(InputStream in){
String result ="";
try{
//创建一个字节数组写入流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ( (length = in.read(buffer)) !=-1) {
out.write(buffer, 0, length);
out.flush();
}
result = out.toString();//将字节流转换成string
out.close();
}catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
最后:
封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。Bitmap 是用于处理由像素数据定义的图像的对象。
还有增加访问Internet权限:
android.permission.INTERNET