HttpURLConnection

来源:互联网 发布:问卷调查如何数据分析 编辑:程序博客网 时间:2024/06/07 03:25

1.HttpURLConnection连接URL

1)创建一个URL对象URL url = new URL(http://www.baidu.com);2)利用HttpURLConnection对象从网络中获取网页数据HttpURLConnection conn = (HttpURLConnection) url.openConnection();3)设置连接超时conn.setConnectTimeout(6*1000);4)对响应码进行判断if (conn.getResponseCode() != 200)    //从Internet获取网页,发送请求,将网页以流的形式读回来5)得到网络返回的输入流InputStream is = conn.getInputStream();6)String result = readData(is, "GBK"); //文件流输入出文件用outStream.write7)conn.disconnect();

总结:
–记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作.
–返回的响应码200,是成功.
–在Android中对文件流的操作和JAVA SE上面是一样的.
–在对大文件的操作时,要将文件写到SDCard上面,不要直接写到手机内存上.
–操作大文件是,要一遍从网络上读,一遍要往SDCard上面写,减少手机内存的使用.这点很重要,面试经常会被问到.
–对文件流操作完,要记得及时关闭.

2.向Internet发送请求参数

步骤:

1)创建URL对象:URL realUrl = new URL(requestUrl);2)通过HttpURLConnection对象,向网络地址发送请求HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();3)设置容许输出:conn.setDoOutput(true);4)设置不使用缓存:conn.setUseCaches(false);5)设置使用POST的方式发送:conn.setRequestMethod("POST");6)设置维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");7)设置文件字符集:conn.setRequestProperty("Charset", "UTF-8");8)设置文件长度:conn.setRequestProperty("Content-Length", String.valueOf(data.length));9)设置文件类型:conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");10)以流的方式输出.

总结:
–发送POST请求必须设置允许输出
–不要使用缓存,容易出现问题.
–在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头.

3.向Internet发送xml数据

XML格式是通信的标准语言,Android系统也可以通过发送XML文件传输数据.

1)将生成的XML文件写入到byte数组中,并设置为UTF-8:byte[] xmlbyte = xml.toString().getBytes("UTF-8");2)创建URL对象,并指定地址和参数:URL url = new URL("http://……");3)获得链接:HttpURLConnection conn = (HttpURLConnection) url.openConnection();4)设置连接超时:conn.setConnectTimeout(6* 1000);5)设置允许输出conn.setDoOutput(true);6)设置不使用缓存:conn.setUseCaches(false);7)设置以POST方式传输:conn.setRequestMethod("POST");    8)维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");9)设置字符集:conn.setRequestProperty("Charset", "UTF-8");10)设置文件的总长度:conn.setRequestProperty("Content-Length",String.valueOf(xmlbyte.length));11)设置文件类型:conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");12)以文件流的方式发送xml数据:outStream.write(xmlbyte);

总结:
–我们使用的是用HTML的方式传输文件,这个方式只能传输一般在5M一下的文件.
–传输大文件不适合用HTML的方式,传输大文件我们要面向Socket编程.确保程序的稳定性
–将地址和参数存到byte数组中:byte[] data = params.toString().getBytes();

例子:

get请求返回字节流

public static InputStream doHttpByGet(String path){        InputStream inputStream = null;        try {            URL url = new URL(path);            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            connection.setRequestMethod("GET");            connection.setDoInput(true);            //GET 请求不需要设置该项,输入输出是相对于程序自身而言的            connection.setDoOutput(true);            //设置请求超时的时间            connection.setReadTimeout(5 * 1000);            //获取请求码,请求码为200说明请求成功            if(connection.getResponseCode()==200){                inputStream = connection.getInputStream();                return inputStream;            }        } catch (java.io.IOException e) {            e.printStackTrace();        }        return null;    }

将流取出取得数据

public static String getDataByInputStream(InputStream inputStream){        ByteArrayOutputStream byteArrayOutputStream = null;        int len = 0;        byte b[] = new byte[1024];        try {            byteArrayOutputStream = new ByteArrayOutputStream();            while((len = inputStream.read(b))!=-1){                byteArrayOutputStream.write(b,0,len);            }            return byteArrayOutputStream.toString();        } catch (IOException e) {            e.printStackTrace();        }finally {            if(inputStream == null){                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return null;    }

注意:
访问网络时一定要做的两件事:
1、添加权限

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

2、要在子线程中去访问网络,否则抛异常:

一定不要忘了start(),否则没有反应

new Thread(new Runnable() {            @Override            public void run() {              //TODO 调用以上的两个方法            }        }).start();
0 0
原创粉丝点击