Android Http通信(HttpURLConnection)

来源:互联网 发布:扶贫软件 编辑:程序博客网 时间:2024/05/16 06:09

1.使用java.net.URL封装HTTP资源的url,并使用openConnection方法获得HttpURLConnection对象

URL URL=new URL("http://http://blog.csdn.net/u013290075");HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();

2.设置请求方法,例如POST,GET等

 httpURLConnection.setRequestMethod("GET");

要注意的是,setRequestMethod参数必须大写,例如POST,GET等
3.设置输入输出及其他开关.如果要读取HTTP资源或者向服务端上传数据,需进行如下设置

//读取http资源,需将setDoInput方法参数值设为truehttpURLConnection.setDoInput(true);//上传数据,需将setOutInput方法参数值设为truehttpURLConnection.setOutInput(true);

HttpURLConnection类还包含更多的选项,如下面的代码可以禁止HttpURLConnection使用缓存

httpURLConnection.setUseCaches(false);

4.设置HTTP请求头,很多情况下要设置HTTP请求头,如下面代码设置了Charset的请求头为UTF8

httpURLConnection.setRequestProperty("Charset", "UTF-8");

5.读入和输出数据

InputStream in=httpURLConnection.getInputStream();OutputStream os=httpURLConnection.getOutputStream();

6.显式关闭输入输出流

in.close();os.close();
0 0
原创粉丝点击