您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection介绍

2016-06-22 15:10 477 查看
HttpURLConnection简介

HttpURLConnection是URLConnection的子类,每个HttpURLConnection 实例都可用于生成单个请求

 

HttpUrlConnection设置

httpUrlConnection网络请求设置分为两部分,第一部分是请求头,第二部分是请求内容。

HttpUrlConnection在设置连接前,必须设置好请求头,即调用connection()前设置好请求头,请求头重包括网络请求的各种配置,例如超时时间,是否可以读入、写出;请求模式(post、get等)。HttpUrlConnection可以获取输出流,通过输出流将请求内容发送给接收端,然后在通过HttpUrlConnection获取一个输入流,用于接收返回的内容。

Get和post请求

Get请求可以直接拼接url 参数和请求地址之间用?分割,参数之间使用&连接

Post请求的参数是通过输出流输出到接收端的。不需要使用?进行分割,但参数之间仍然使用&连接。

传递数据

当调用connection()时只是建立了一个连接,当获取输出流进行输出时才正式传递参数。

网路超时时间设置

HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序卡死不能继续执行,在jdk1.5中,

setConnectTimeout:设置连接主机超时(单位:毫秒) ,setReadTimeout:设置从主机读取数据超时(单位:毫秒),在JDK1.4.2环境下,设置了defaultReadTimeout的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求,出现一次请求调用

HttpURLConnection简介之get和post请求

URLConnection是个抽象类,HttpURLConnection是URLConnection类的子类,
URLConnection与HttpURLConnection都是抽象类,无法直接实例化对象。其对象主要通过URL的openConnection()方法获得,创建一个httpURLConnection连接的代码如下所示:

–URL url = new UR(“http://www.baidu.com”);

–HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

连接之前我们可以对其一些属性进行设置,例如超时时间等。

下面对HttpURLConnetcion实例的属性设置:

•//设置输入/输出流

–connection.setDoOutput(true);

–connection.setDoInput(true);

•//设置请求的方式为Get或者Post

–connection.setRequestMethod(“GET”);

–connection.setRequestMethod(“POST”);

•//在设置POST方式时要注意,POST请求方式不能够使用缓存

–connection.setUseCaches(false);

 

HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。

 

利用HttpURLConnection来服务器交互的基本过程:

1. 通过网址获取网络连接的url对象(直接new)(若为get或post有要求的连接要求必须是编码以后的请求,URLEncoder类的encode方法)

2. 通过url获取网络连接(httpUrlConnection)对象

3. 设置请求方式

(1) 不设置时是默认为get请求      

(2) 设置get时url.setRequestMethod("GET");此时获取连接的url必须是?pwd=””&name=””&…

(3) 设置post  url.setRequestMethod("POST");

还必须设置content_length(要求的长度)和content_type

4. 设置读取时间限制url.setReadTimeout(5000);

5. 获取响应模式 url.getResponseCode();返回int值 有200连接正常  400客户端有错误
 500是服务器端有错误  404文件不存在

6. 在响应为200时才获取文件流getInputeStream字节输入流InputeStream读取流的内容while循环读入
输入流有read方法可以读入到byte[]数组,返回int值,为-1时读取结束

While中每次都添加到StringBuffer对象中从而获取字符串,若为json数据则可进行数据解析

 

 

//HttpURLConnection的get请求
    public
static
StringgetHttpURLConnection(String urlString,String params){
        Stringresult = null;
        try {
            URLurl=newURL(urlString+"?"+params);
            HttpURLConnectionconnection=(HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//设置可输入
            connection.setDoOutput(true);//设置可以输出
            // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)  
            connection.setRequestProperty("Content-type","application/x-java-serialized-object");
            connection.setRequestMethod("GET");//设置请求方式//必须是大写
            connection.setConnectTimeout(5000);//设置连接超时时间。
            connection.setReadTimeout(5000);//设置读数据的超时时间
            // Post 请求不能使用缓存  
            connection.setUseCaches(true); 
            connection.connect();//连接服务器
            BufferedReaderreader=newBufferedReader(newInputStreamReader(connection.getInputStream()));
            Stringdata;
            StringBuilderbuilder=newStringBuilder();
            while((data=reader.readLine())!=null){
                builder.append(data);
            }
            result=builder.toString();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

//HttpURLConnection的post请求
    public
static
StringpostHttpUrlConnection(String urlString,String params){
        Stringresult=null;
        try{
            URLurl=newURL(urlString);
            HttpURLConnectionconnection=(HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//设置可输入
            connection.setDoOutput(true);//设置可以输出
            connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");//必须设置只有设置后服务器端才会获取参数
            connection.setRequestProperty("Content-Length",params.length()+"");//设置文件长度
            connection.setRequestMethod("POST");//设置请求方式//必须是大写
            connection.setConnectTimeout(5000);//设置连接超时时间。
            connection.setReadTimeout(5000);//设置读数据的超时时间
            // Post 请求不能使用缓存  
            connection.setUseCaches(false); 
            /*byte[] newbyte=params.getBytes();//通过参数字符串获取字节数学组,将参数字节传递过去
            connection.setRequestProperty("Content-Length",newbyte.length+ "");//设置文件长度
            OutputStreamwriter=connection.getOutputStream();
            writer.write(newbyte);
            writer.flush();*/
            BufferedWriterwriter=newBufferedWriter(newOutputStreamWriter(connection.getOutputStream()));
            writer.write(params);
            writer.flush();
            int responseCode =connection.getResponseCode();//
            if (responseCode == 200) {
              //请求成功
              BufferedReaderreader=newBufferedReader(newInputStreamReader(connection.getInputStream()));
            String data;
            StringBuilder builder=new StringBuilder();
            while((data=reader.readLine())!=null){
                builder.append(data);
            }
            result=builder.toString();
             } else
if
(responseCode == 400) {
                result = "客户端有错误";
             } else
if
(responseCode == 500) {
                result = "服务器端有错误";
             } else
if
(responseCode == 404) {
                result = "url不存在";
             }
           
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }

//HttpURLConnection下载图片
    public
static
Bitmap getImatge(Stringurl){
        Bitmapbitmap=null;
        try{
            URLurls=newURL(url);
            HttpURLConnectionconn=(HttpURLConnection) urls.openConnection();
            bitmap=BitmapFactory.decodeStream(conn.getInputStream());
        }catch(Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }

//HttpURLConnection上传图片
    public
void
uploadFile() {
        Stringend = "\r\n";
        StringtwoHyphens = "--";
        Stringboundary = "*****";
        try {
            URLurl = newURL(actionUrl);
            HttpURLConnectioncon = (HttpURLConnection) url.openConnection();
            /* 允许Input、Output,不使用Cache
*/
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            /* 设置传送的method=POST */
            con.setRequestMethod("POST");
            /* setRequestProperty */
            con.setRequestProperty("Connection","Keep-Alive");
            con.setRequestProperty("Charset","UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            /* 设置DataOutputStream*/
            DataOutputStreamds = newDataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens+ boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    +"name=\"file1\";filename=\"" +newName+"\""+ end);
            ds.writeBytes(end);
            /* 取得文件的FileInputStream *///读入响应
            FileInputStreamfStream = newFileInputStream(uploadFile);
            /* 设置每次写入1024bytes */
            int buff
c0b0
erSize = 1024;
            byte[] buffer =newbyte[bufferSize];
            int length = -1;
            while ((length =fStream.read(buffer)) != -1) {
                ds.write(buffer,0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens+ boundary + twoHyphens + end);
 
            fStream.close();
            ds.flush();
            /* 取得Response内容 */
            InputStreamis = con.getInputStream();
            int ch;
            StringBufferb = newStringBuffer();
            while ((ch = is.read()) !=-1) {
                b.append((char) ch);
            }
            Messagemsg = newMessage();
            msg.what =
WIN;
            msg.obj = b.toString();
            handler.sendMessage(msg);
            ds.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

关于HttpURLConnection的多线程下载,没有具体的例子,下载的文件可以通过HttpURLConnection.getContentLength();获取文件的大小,然后将长度除以线程数获取每个想线程加载的数据长度,通过skip()方法跳过指定的字节数,为了准确的跳过指定的字节数,一般使用skipFully(),每个线程加载加载填充已经定义好的文件(用于保存下载的文件)的一部分。而关于断点续传则通过下载时同时生成两个文件,一个是下载的文件,一个是用于保存下载的字节数的文件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息