视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
多线程上传和下载HttpURLConnection
2025-10-05 17:12:31 责编:小OO
文档
0.操作说明:

1.建议一个web项目

2.在运行main方法前一定要现发布web项目,以确保向服务器的连接可用

1.利用HttpURLConnection进行多线程下载

package com.ykp.down;

import java.io.IOException;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;

/**

 * 多线程下载

 * @author 燕鲲鹏

 * @version 1.0 2012-8-18

 */

public class Down {

    public static void main(String[] args) throws Exception {

        //1.声明url

        URL url = new URL("http://127.0.0.1:8087/day26/aa.avi");

        //2.获得连接

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

        //3.设置请求的方式

        con.setRequestMethod("GET");

        //4.设置不缓存

        con.setUseCaches(false);

        //5.访问成功了,获得http状态码

        int code = con.getResponseCode();

        //6.对状态吗进行判断

        if(200 == code){//访问成功

            //定义保存的文件名

            String fileName = "E:/aa.avi";

            //从http头信息获得文件长度

            int length = con.getContentLength();

            //声明一个临时文件

            RandomAccessFile file = new RandomAccessFile(fileName, "rw");

            //设置文件大小

            file.setLength(length);

            //关闭临时文件

            file.close();

            System.err.println("临时文件的大小为:"+length);

            //计算每个线程应该下载的大小

            int block = length/3==0?length/3:length/3+1;

            //启动三个线程

            for(int i=0;i<3;i++){

                //计算每个线程开始的位置和结束的位置

                int start = i*block;

                int end = start+block-1;

                //输出位置信息

                System.err.println(i+":  "+start+"   ,"+end);

                //开启线程

                new DownThread(url, start, end, fileName).start();

            }

        }

    }

    

    

    //设置线程

    static class DownThread extends Thread{

        //定义成员变量

        private URL url;

        private int start;

        private int end;

        private String fileName;

        public DownThread(URL url, int start, int end, String fileName) {

            this.url = url;

            this.start = start;

            this.end = end;

            this.fileName = fileName;

        }

        @Override

        public void run() {

            //开始文件下载

            try {

                //获得url连接

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

                //设置连接的属性

                //设置HttpURLConnection的请求方式为get

                con.setRequestMethod("GET");

                //设置是否缓存

                con.setUseCaches(false);

                //设置url为输入流,即可以接收服务器的数据

                con.setDoInput(true);

                //设置url的request的请求属性,设置下载的开始和结束位置

                con.setRequestProperty("Range", "bytes="+start+"-"+end);// Range:bytes=0-10

                

                //获得http的状态码

                int code = con.getResponseCode();

                //开始下载

                if(206 == code){//206 Partial Content(206(部分内容)服务器成功处理了部分 GET 请求。)

                    //产生一个随即访问文件 

                    RandomAccessFile file = new RandomAccessFile(fileName, "rw");

                    //设这开设的位置

                    file.seek(start);

                    //开始下载

                    //获得con的输入流对象,即获得需要下载的内容

                    InputStream in = con.getInputStream();

                    //将输入流字节码依次写入到所创建的文件中

                    byte[] b = new byte[1024];//每次读取的最大长度为1Kb

                    int len = 0;

                    while((len = in.read(b)) != -1){

                        file.write(b, 0, len);

                    }

                    //关闭文件

                    file.close();

                }

                

                System.err.println("线程:"+this.getName()+"   下载成功");

            } catch (IOException e) {

                e.printStackTrace();

            }

            

        }

    }

}

2. 通过HttpURLConnection在客户端向服务器发送请求,并获取服务器数据

package com.ykp.httpURLConnection;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

/**

 * 通过HttpURLConnection在客户端向服务器发送请求,并获取服务器数据

 * @author 燕鲲鹏

 * @version 1.0 2012-8-18

 */

public class URLDemo1 {

    public static void main(String[] args) throws Exception {

        //获得url对象

        URL url = new URL("http://localhost:8087/day26/bookstore/create/1.sql");

        //通过java.net.URL类来获得httpUrlConnection对象,建立与服务器的连接,打开url的连接

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

        //获得服务器的输入流

        InputStream in = con.getInputStream();

        //定义readerbuffer对象

        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        //循环遍历读出的信息

        String str = "";

        while((str=br.readLine())!=null){

            System.err.println(str);

        }

        //断开连接

        con.disconnect();

    }

}

3. 向服务器发消息默认请求到doGet方式

package com.ykp.httpURLConnection;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

/**

 * 向服务器发消息默认请求到doGet方式

 * @author 燕鲲鹏

 * @version 1.0 2012-8-18

 */

public class URLDemo2 {

    public static void main(String[] args) throws Exception {

        //获得url对象

        URL url = new URL("http://localhost:8087/day26");

        //通过java.net.URL类来获得httpUrlConnection对象,建立与服务器的连接,打开url的连接

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

        //打开可以向服务器发消息

        con.setDoOutput(true);

        //获得输出流

        OutputStream out = con.getOutputStream();

        //向服务器发送数据,只能写字节码

        out.write("name=ykp".getBytes());

        //获得状态码,以表示请求完成

        int code = con.getResponseCode();

        //输出相应的状态码

        System.err.println("code-->"+code);

        //断开连接

        con.disconnect();

    }

}

4. 通过post方式来发送,解决中文乱码

1.java源代码

package com.ykp.httpURLConnection;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import org.junit.Test;

    @Test

    public void URLGet() throws Exception {

        //获得url对象

        URL url = new URL("http://localhost:8087/day26/OneServlet?name=ykp燕鲲鹏");

        //通过java.net.URL类来获得httpUrlConnection对象,建立与服务器的连接,打开url的连接

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

        //2、通过设置请求头处理中文参数的乱码

        con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

        con.setRequestProperty("encoding", "UTF-8");

        con.setRequestMethod("GET");

        con.setDoInput(true);

        con.setDoOutput(true);

        //获得状态码,以表示请求完成

        int code = con.getResponseCode();

        if(code == 200){

            InputStream in = con.getInputStream();

            byte[] b = new byte[1024];

            int len = 0;

            while((len=in.read(b))!=-1){

                System.err.println(new String(b, 0, len));

            }

        }

//        

//        System.err.println("jjj");

        //断开连接

        con.disconnect();

    }

    /**

     * 通过post方式来发送

     */

    @Test

    public void URLPost() throws Exception {

        //获得url对象

        URL url = new URL("http://localhost:8087/day26/OneServlet?");

        //通过java.net.URL类来获得httpUrlConnection对象,建立与服务器的连接,打开url的连接

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

        //2、通过设置请求头处理中文参数的乱码

        con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

        con.setRequestProperty("encoding", "UTF-8");

        //设置相应的方式为post

        con.setRequestMethod("POST");

        //设置可以输入和输出

        con.setDoInput(true);

        con.setDoOutput(true);

        //获得输出流,来向服务器发送数据

        OutputStream out = con.getOutputStream();

        //向服务器发送数据

        out.write("name=ykp&addr=hh北京".getBytes());

        //关闭输出流

        out.close();

        //获得状态码,以表示请求完成

        int code = con.getResponseCode();

        if(code == 200){

            //获得输入流,来接收服务器发送的数据

            InputStream in = con.getInputStream();

            byte[] b = new byte[1024];

            int len = 0;

            //在客户端输出从服务器接收的数据

            while((len=in.read(b))!=-1){

                System.err.println(new String(b, 0, len));

            }

        }

        

//        System.err.println("jjj");

        //断开连接

        con.disconnect();

    }

}

2.servlet源代码

package com.ykp.servlet;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class OneServlet extends HttpServlet {

    

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 

            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        System.err.println("OneServlet------>get");

        String name = request.getParameter("name");

        System.err.println("name-->"+name);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 

            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        System.err.println("OneServlet------>post");

        String name = request.getParameter("name");

        String addr = request.getParameter("addr");

        System.err.println("name-->"+name);

        System.err.println("addr-->"+addr);

        

    }

}下载本文

显示全文
专题