Android入门教程 HttpURLConnection的用法 HTTP请求

写在前面:
android使用网络一定记得加上网络访问权限

<uses-permission android:name="android.permission.INTERNET" />

一、使用HttpURLConnection发送网络请求

1、get方式发送请求

step1:创建URL对象
step2:通过URL对象调用openConnection()方法获得HttpURLConnection对象
step3:HttpURLConnection对象设置其他连接属性
step4:HttpURLConnection对象调用getInputStream()方法向服务器发送http请求 并获取到服务器返回的输入流
step5:读取输入流,转换成String字符串

注意:
网络请求,通常耗时较长,所以不能在主线程中进行,需要单独开一个子线程进行网络请求

代码示例

public class MainActivity extends Activity {

    private TextView webTextView;
    private String webText;
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if(msg.what==1){
                webTextView.setText(webText);
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webTextView = (TextView) findViewById(R.id.web_text);
        //创建线程对象
        MyThread mThread = new MyThread();
        //启动线程
        new Thread(mThread).start();
    }
    /**
     * 定义一个子线程,在子线程中访问网络
     * @author jiangjunjie
     *
     */
    private class MyThread implements Runnable{

        @Override
        public void run() {
            try {
                URL url = new URL("http://www.baidu.com");
                HttpURLConnection mConnection = (HttpURLConnection) url.openConnection();
                mConnection.setConnectTimeout(10000);//设置连接超时

                //创建输入流
                InputStream in = null;
                //判断连接返回码
                if(mConnection.getResponseCode()==200){
                    //返回码是200时,表明连接成功
                    in = mConnection.getInputStream();
                }
                //创建输入流读取对象
                InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
                //输入流缓存读取
                BufferedReader bufferedReader = new BufferedReader(inReader);
                StringBuffer sb = new StringBuffer();
                String temp = null;
                //输入流转换成String
                while((temp=bufferedReader.readLine())!=null){
                    sb.append(temp);
                }
                webText = sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //Handler创建消息对象
            Message msg = mHandler.obtainMessage();
            msg.what = 1;
            //发送Handler消息
            mHandler.sendMessage(msg);
        }

    }

}

2、post方式发送请求

post请求方式和get方式步骤类似,只需添加一句

mConnection.setRequestMethod("POST");

二、使用HttpURLConnection加载网络图片

加载网络图片,需要用到Bitmap对象。
加载网络图片有时也需耗时较长时间,所以也应该异步加载。
在此,以AsyncTask为例。

效果图
这里写图片描述
ShowWebPicActivity代码示例

public class ShowWebPicActivity extends Activity {

    Button showBtn;
    ImageView webimgView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_web_pic);

        bindID();

        showBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                DownloadImgTask task = new DownloadImgTask(ShowWebPicActivity.this, showBtn, webimgView);
                task.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg");
            }
        });
    }

    private void bindID() {
        showBtn = (Button) findViewById(R.id.show_btn);
        webimgView = (ImageView) findViewById(R.id.pic_img);
    }
}

DownloadImgTask代码

public class DownloadImgTask extends AsyncTask<String, Integer, Integer>{

    private Context context;
    private Button btn;
    private ImageView imageView;
    //加载网络图片需要用到Bitmap对象
    private Bitmap bitmap;

    public DownloadImgTask(Context context,Button btn,ImageView imgview) {
        this.context = context;
        this.btn = btn;
        this.imageView = imgview;

    }

    @Override
    protected Integer doInBackground(String... params) {
        try {
            //创建URL对象
            URL url = new URL(params[0]);
            //通过URL对象得到HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //得到输入流
            InputStream inputStream = connection.getInputStream();

            bitmap = BitmapFactory.decodeStream(inputStream);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        switch (result) {
        case 1:
            imageView.setImageBitmap(bitmap);
            break;

        default:
            break;
        }
    }

}

三、使用HttpURLConnection下载网络资源

下载网络资源用到的知识点,除了网络资源访问,还需要用到文件操作的知识,比如判断文件是否存在、创建目录、创建文件等等。

activity_download.xml布局文件代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ProgressBar 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleHorizontal"
        />
    <Button 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下载"
        android:id="@+id/downloadBtn"
        android:layout_below="@id/progressbar"
        />
</RelativeLayout>

DownloadActivity代码

public class DownloadActivity extends Activity {

    ProgressBar progressBar;
    Button downloadBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        bindID();


        downloadBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                downloadBtn.setEnabled(false);
                //构造方法初始化
                DownLoadTask dTask = new DownLoadTask(DownloadActivity.this,downloadBtn,progressBar);
                //执行任务
                dTask.execute("http://img1.bitautoimg.com/bitauto/2012/09/17/a50cdcf8-1a2a-418b-b7be-d81f36ab12ee.jpg","fra.jpg");
            }
        });
    }

    private void bindID() {
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        downloadBtn = (Button) findViewById(R.id.downloadBtn);

    }
}

DownLoadTask代码

public class DownLoadTask extends AsyncTask<String, Integer, Integer> {

    private Context context;
    private Button btn;
    private ProgressBar pBar;
    private String SDPATH = "";
    private String PATH="";
    /**
     * 构造方法
     * @param context Activity上下文环境
     * @param btn   下载按钮
     * @param pBar  进度条
     */
    public DownLoadTask(Context context,Button btn,ProgressBar pBar) {
        this.context = context;
        this.btn = btn;
        this.pBar = pBar;
        this.SDPATH = Environment.getExternalStorageDirectory() + "/";
        this.PATH = this.SDPATH+"download_pic/";
        System.out.println("PATH***:"+PATH);
    }

    @Override
    protected Integer doInBackground(String... params) {
        //定义输入流和输出流对象
        InputStream inputStream = null;
        OutputStream outputStream = null;
        //定义文件对象
        File file = null;
        //判断文件是否存在
        if (isFileExists(PATH+params[1])) {
            //如果存在,直接返回,执行onPostExecute方法
            return 1;
        }
        try {
            //创建URL对象
            URL url = new URL(params[0]);
            //通过URL对象创建HTTP连接
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            //判断返回码
            if (httpUrlConnection.getResponseCode() == 200) {
                inputStream = httpUrlConnection.getInputStream();
                // 更新进度条(设置进度条总长度)
                publishProgress(-2, httpUrlConnection.getContentLength());
            } else {
                // 下载有误,网络连接错误
                publishProgress(-1);
            }
            //创建目录
            createDir(PATH);
            //创建文件
            file = createFile(PATH+params[1]);
            //创建输出流
            outputStream = new FileOutputStream(file);
            //创建缓冲区
            byte buffer[] = new byte[4*1024];
            int length = 0;
            int sum = 0;
            while((length = inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,length);
                //已经下载的长度
                sum+=length;
                //更新进度条
                publishProgress(0,sum);
            }
            outputStream.flush();//强制把缓冲区的数据写入到文件并清空缓冲区

        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 下载过程中执行此方法
     * @param values
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        switch (values[0]) {
        case 0:
            pBar.setProgress(values[1]);
            break;
        case -1:
            Toast.makeText(context, "网络连接错误,请检查下载链接是否正确", Toast.LENGTH_LONG).show();
            break;
        case -2:
            pBar.setMax(values[1]);
            break;
        default:
            break;
        }
    }

    /**
     * 下载完成后执行此方法
     * @param result
     */
    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        btn.setEnabled(true);
        switch (result) {
        case 1:
            Toast.makeText(context, "文件已存在", Toast.LENGTH_LONG).show();
            break;

        default:
            break;
        }
    }

    /**
     * 工具方法——判断文件已存在
     * 
     * @return
     */
    private boolean isFileExists(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            // 文件已存在
            return true;
        }
        return false;
    }
    /**
     * 工具方法——创建目录
     */
    private boolean createDir(String dirName) {
        File file = new File(dirName);
        boolean isCreateDir = file.mkdir();
        return isCreateDir;
    }
    /**
     * 工具方法——创建文件
     * @param string
     */
    private File createFile(String fileName) {
        File file = new File(fileName);
        boolean isCreateFile  = false;
        try {
            isCreateFile = file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值