使用HttpURLConnection

HttpURLConnection继承了URLConnection,差别在与HttpURLConnection仅仅针对Http连接。他在URLConnecion的基础上提供了一些便捷的方法。
使用的步骤:
1.创建URL对象

 URL url = new URL(path);

2.创建HttpURLConnection对象

 HttpURLConnection conn = (HttpURLConnection) url.openConnection();

3.设置此对象的属性

  conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
                "Accept","*/*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");

4.建立连接

conn.connect();
/*
* 不论是否明确调用connect()方法,通过setRequestProperty(name,value)设置的属性都生效了,那这是为什么呢?
经过一番查证,原来是在调用getInputStream()方法中会检查连接是否已经建立,如果没有建立,则会调用connect()方法,所以疑惑解开了!
原来是在调用getInputStream()的时候会做连接是否建立的检查!
* */

5.向服务器写数据

  OutputStream outputStream=conn.getOutputStream();
                            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outputStream);
                            BufferedWriter bufferedWriter=new BufferedWriter(outputStreamWriter);
                            //这段是传给服务器的数据
                            bufferedWriter.write("keyfrom=httpget11112222&key=457968782&type=data&doctype=xml&version=1.1&q=good");
                            bufferedWriter.flush();

6.向服务器读数据

  InputStream inputStream= connection.getInputStream();
                            InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
                            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                            String line;
                            while((line=bufferedReader.readLine())!=null){
                                System.out.println(line);
                            }
                            bufferedReader.close();
                            inputStreamReader.close();
                            inputStream.close();

值得注意的是要是既要向服务器读数据也向服务器写数据,要先写后读。
下面我们用一个多线程下载的例子来演示
DownUtil.java

package org.crazyit.http;

import java.io.InputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownUtil
{
    // 定义下载资源的路径
    private String path;
    // 指定所下载的文件的保存位置
    private String targetFile;
    // 定义需要使用多少线程下载资源
    private int threadNum;
    // 定义下载的线程对象
    private DownThread[] threads;
    // 定义下载的文件的总大小
    private int fileSize;
    public DownUtil(String path, String targetFile, int threadNum)
    {
        this.path = path;
        this.threadNum = threadNum;
        // 初始化threads数组
        threads = new DownThread[threadNum];
        this.targetFile = targetFile;
    }
    public void download() throws Exception
    {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
                "Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        // 得到文件大小
        fileSize = conn.getContentLength();
        conn.disconnect();
        int currentPartSize = fileSize / threadNum + 1;
        RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
        // 设置本地文件的大小
        file.setLength(fileSize);
        file.close();
        for (int i = 0; i < threadNum; i++)
        {
            // 计算每条线程的下载的开始位置
            int startPos = i * currentPartSize;
            // 每个线程使用一个RandomAccessFile进行下载
            RandomAccessFile currentPart = new RandomAccessFile(targetFile,
                    "rw");
            // 定位该线程的下载位置
            currentPart.seek(startPos);
            // 创建下载线程
            threads[i] = new DownThread(startPos, currentPartSize,
                    currentPart);
            // 启动下载线程
            threads[i].start();
        }
    }
    // 获取下载的完成百分比
    public double getCompleteRate()
    {
        // 统计多条线程已经下载的总大小
        int sumSize = 0;
        for (int i = 0; i < threadNum; i++)
        {
            sumSize += threads[i].length;
        }
        // 返回已经完成的百分比
        return sumSize * 1.0 / fileSize;
    }
    private class DownThread extends Thread
    {
        // 当前线程的下载位置
        private int startPos;
        // 定义当前线程负责下载的文件大小
        private int currentPartSize;
        // 当前线程需要下载的文件块
        private RandomAccessFile currentPart;
        // 定义已经该线程已下载的字节数
        public int length;
        public DownThread(int startPos, int currentPartSize,
                          RandomAccessFile currentPart)
        {
            this.startPos = startPos;
            this.currentPartSize = currentPartSize;
            this.currentPart = currentPart;
        }
        @Override
        public void run()
        {
            try
            {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection)url
                        .openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty(
                        "Accept",
                        "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                                + "application/x-shockwave-flash, application/xaml+xml, "
                                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                                + "application/x-ms-application, application/vnd.ms-excel, "
                                + "application/vnd.ms-powerpoint, application/msword, */*");
                conn.setRequestProperty("Accept-Language", "zh-CN");
                //"Accept"是HTTP协议定义的,表示客户端可接收的文档类型,和java无关,任何语言实现HTTP协议都要实现这个。
                //   */*就是所有类型文档了
                conn.setRequestProperty("Charset", "UTF-8");
                InputStream inStream = conn.getInputStream();
                // 跳过startPos个字节,表明该线程只下载自己负责的那部分文件
                skipFully(inStream, this.startPos);
//              inStream.skip(this.startPos);
                byte[] buffer = new byte[1024];
                int hasRead = 0;
                // 读取网络数据,并写入本地文件
                while (length < currentPartSize
                        && (hasRead = inStream.read(buffer)) > 0)
                {
                    currentPart.write(buffer, 0, hasRead);
                    // 累计该线程下载的总大小
                    length += hasRead;
                }
                currentPart.close();
                inStream.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    // 定义一个为InputStream跳过bytes字节的方法
    public static void skipFully(InputStream in, long bytes) throws IOException
    {
        long remainning = bytes;
        long len = 0;
        while (remainning > 0)
        {
            len = in.skip(remainning);
            remainning -= len;
        }
    }
}

MainActivity.java

package org.crazyit.http;


        import android.app.Activity;
        import android.os.Bundle;
        import android.os.Handler;
        import android.os.Message;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ProgressBar;

        import java.util.Timer;
        import java.util.TimerTask;


public class LearnHttpURLConnection extends Activity
{
    EditText url;
    EditText target;
    Button downBn;
    ProgressBar bar;
    DownUtil downUtil;
    private int mDownStatus;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learn_http_urlconnection);
        // 获取程序界面中的三个界面控件
        url = (EditText) findViewById(R.id.url);
        target = (EditText) findViewById(R.id.target);
        downBn = (Button) findViewById(R.id.down);
        bar = (ProgressBar) findViewById(R.id.bar);
        // 创建一个Handler对象
        final Handler handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                  //handler在此处根据计算传递回来的结果并进行UI操作
                if (msg.what == 0x123)
                {
                    bar.setProgress(mDownStatus);
                }
            }
        };
        downBn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // 初始化DownUtil对象(最后一个参数指定线程数)
                downUtil = new DownUtil(url.getText().toString(),
                        target.getText().toString(), 6);
                new Thread()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            // 在线程里面启动下载的类,开始下载
                            downUtil.download();
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        // 定义每秒调度获取一次系统的完成进度
                        final Timer timer = new Timer();
                        timer.schedule(new TimerTask()
                        {
                            @Override
                            public void run()
                            {
                                // 获取下载任务的完成比例
                                double completeRate = downUtil
                                        . getCompleteRate();
                                mDownStatus = (int) (completeRate * 100);
                                //handler通过在线程里进行费事操作,然后在发送消息
                                // 发送消息通知界面更新进度条
                                handler.sendEmptyMessage(0x123);
                                // 下载完全后取消任务调度
                                if (mDownStatus >= 100)
                                {
                                    timer.cancel();
                                }
                            }
                        }, 0, 100);
                    }
                }.start();
            }
        });
    }
}



activity_learn_http_urlconnection.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="org.crazyit.http.LearnHttpURLConnection"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="要下载的资源的URL:"
        />
    <EditText
        android:id="@+id/url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://www.crazyit.org/attachment.php?aid=MTA5M3w5OTUyNGEzNHwxMzUyODIzNDM0fDU0MDQ2MHNzd1p5Y25KVkFDYXYzUS9uMEpOUnBKRjFCbFpkTldleWpRYzZUbzVV"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="目标文件:"
        />
    <EditText
        android:id="@+id/target"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="/mnt/sdcard/a.chm"
        />
    <Button
        android:id="@+id/down"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="down"
        />
    <!-- 定义一个水平进度条,用于显示下载进度 -->
    <ProgressBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        style="?android:attr/progressBarStyleHorizontal"
        />
</LinearLayout>
为了使用HttpURLConnection来发送和接收HTTP请求和响应,您需要按照以下步骤操作: 1. 创建HttpURLConnection对象,并将其连接到URL对象。例如: URL url = new URL("http://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 2. 设置请求方法和连接属性,如连接超时和读取超时。例如: conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); 3. 添加请求头(可选)。例如: conn.setRequestProperty("User-Agent", "Android"); conn.setRequestProperty("Content-Type", "application/json"); 4. 如果POST请求,添加请求体。例如: String requestBody = "{\"username\":\"user123\",\"password\":\"pass123\"}"; OutputStream outputStream = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); 5. 发送请求,获取响应码和响应数据。例如: int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder responseData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { responseData.append(line); } reader.close(); inputStream.close(); String responseString = responseData.toString(); } 以上是使用HttpURLConnection发送和接收HTTP请求和响应的基本步骤。具体实现需根据具体的业务需求和网络情况进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值