(Android网络1)HttpURLConnection
来源:互联网 发布:异或符号 java 编辑:程序博客网 时间:2024/06/03 17:29
前言:
今天,开始坚持每天写一篇文章,通过这种方式,记录下自己在安卓开发之路上的历程,希望通过这种方式,提升自己的开发水平,并且养成良好的习惯,在未来,遇见更好的自己!Begining ,Life's a struggle.
1.HttpURLConnection介绍(引自百度)
URLconnection是个抽象类,它有两个直接子类分别为HttpURLConnection和JarURLConnection,另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指定特定地址的URL实例,每个HttpURLConnection实例都可以生成单个请求,但是其他实例可以透明的共享连接到HTTP服务器的基础网络,请求后在HttpURLConnection的InputStream或OutputStream上调用close()方法可以释放与此实例相关的网络资源,但是对共享的持久连接没有任何影响,如果在调用disconnect()时持久连接空闲,则可能关闭基础套字节(总结:HttpURLConnection需要通过构造后的URL生成请求,获取到InputStream或OutputStream.InputStream和OutputStream可调用close()方法释放资源,但对HttpURLConnection没有影响,HttpURLConnection可通过disconnect()进行切断连接)
2.通过实例介绍该类
1.看代码:
try { //新建一个url并传入百度地址,让它访问百度 URL url=new URL("http://www.baidu.com"); //新建一个HttpURLConnection,打开url // (因为url.openConnection()方法返回的是HttpURLConnection的父类URLConnection所以需要强转) HttpURLConnection connection= (HttpURLConnection) url.openConnection(); //设置它的请求方式,以GET方式请求 //http1.0定义了三种请求方式:GET , POST , HEAD //http2.0新增了五种请求方式:OPTIONS , PUT , DELETE ,TRACE , CONNECT connection.setRequestMethod("GET"); //设置它连接超时的时间这里时间以毫秒为单位 connection.setConnectTimeout(3000); //设置它的读取超时的时间这里同样时间以毫秒为单位 connection.setReadTimeout(3000); //建立连接发送请求,获取输入流(通俗点就是输入到程序里面的流) InputStream in=connection.getInputStream(); //将字节流InputStream转换为字符流 BufferedReader reader=new BufferedReader(new InputStreamReader(in)); //用于接收读取到的数据 StringBuffer buffer=new StringBuffer(); String line; //BufferedReader的readLine()方法是阻塞式的, 如果到达流末尾, 就返回null while ((line=reader.readLine())!=null){ //拼接上字符 buffer.append(line); } //将获取到的内容输出到日志 System.out.print(buffer.toString());// Log.d("Test",buffer.toString()); in.close(); connection.disconnect(); } catch (MalformedURLException e) {//主要捕获URL的异常 e.printStackTrace(); } catch (IOException e) {//捕获url.openConnection()异常 e.printStackTrace(); }
2.这里就直接使用测试用例看一下输出的是什么了.
可以看到输出的是百度的html文档里面的内容
3.GET请求和POST请求发送参数:
1.GET请求直接在请求地址里面添加参数:
URL url=new URL("http://www.baidu.com?page=1&name=2");2.POST请求
//发送POST请求必须设置如下两行 connection.setDoInput(true); connection.setDoOutput(true); //获取输出流 PrintWriter printWriter=new PrintWriter(connection.getOutputStream()); //写入参数 格式为: page=1&name=2 printWriter.write("page=1&name=2"); //更新一下缓冲 printWriter.flush();
4.上传和下载文件
1.上传文件(先了解http请求协议)
String BOUNDARY= UUID.randomUUID().toString();//分界线 String PREFIX="--",LINEND="\r\n";//前缀和后缀 String MULTIPART_FROM_DATA="multipart/form-data";//表单数据多部分构成 String CHARSET="utf-8";//编码格式 //不允许用缓存 connection.setUseCaches(false); //发送POST请求必须设置如下两行 connection.setDoInput(true); connection.setDoOutput(true); //设置字符串连接参数 connection.setRequestProperty("Connection","Keep-Alive"); //设置字符编码 connection.setRequestProperty("Charset",CHARSET); //设置请求内容类型 connection.setRequestProperty("Content-Type",MULTIPART_FROM_DATA+";boundary="+BOUNDARY); //获取输出流 OutputStream out=connection.getOutputStream(); /** * 传递文本 */ //拼组文本类型参数,即id=1&name=2 StringBuilder textBuilder=new StringBuilder(); //这里可以循环 textBuilder.append(PREFIX); textBuilder.append(BOUNDARY); textBuilder.append(LINEND); textBuilder.append("Content-Disposition;form-data;name=\"" + "id" + "\"").append(LINEND);//id为key textBuilder.append("Content-Type;text/plain;charset=").append(CHARSET).append(LINEND); textBuilder.append("Content-Transfer-Encoding:8bit").append(LINEND); textBuilder.append(LINEND); textBuilder.append("1");//1为id的值 textBuilder.append(LINEND); out.write(textBuilder.toString().getBytes()); /** * 传递文件 */ //构造文件,传入文件路径 File file=new File("F:/test.txt"); DataInputStream filein=new DataInputStream(new FileInputStream(file)); //这段可以循环 StringBuilder fileBuilder=new StringBuilder(); fileBuilder.append(PREFIX); fileBuilder.append(BOUNDARY); fileBuilder.append(LINEND); fileBuilder.append("Content-Disposition;form-data;name=\"" + "file" + "\";filename=\"").append(file.getName()).append("\"").append(LINEND); fileBuilder.append("Content-Type:application/octet-stream;charset=").append(CHARSET).append(LINEND); fileBuilder.append(LINEND); out.write(fileBuilder.toString().getBytes()); //新建缓冲,将文件的输入流内容写到网络输出流中 int bytes=0; byte[] bytebuffer=new byte[1024]; while ((bytes=filein.read(bytebuffer))!=-1){ out.write(bytebuffer,0,bytes); } filein.close(); out.write(LINEND.getBytes()); /** * 请求结束 */ byte[] end_data=(PREFIX+BOUNDARY+LINEND).getBytes(); out.write(end_data); //刷新缓冲 out.flush();
2.下载文件
//建立连接发送请求,获取输入流(通俗点就是输入到程序里面的流) InputStream in=connection.getInputStream(); //获取文件大小 int fileSize=connection.getContentLength(); //获取文件名 String filePathUrl=connection.getURL().getFile(); String filename=filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar)+1); System.out.println(filename); BufferedInputStream inbuffer=new BufferedInputStream(in); File file=new File("E://"+System.currentTimeMillis()+filename.substring(filename.lastIndexOf("."))); if (!file.exists()){ file.createNewFile(); } FileOutputStream fos=new FileOutputStream(file); byte[] buffer=new byte[1024]; int line=0; int localsize=0; while ((line=inbuffer.read(buffer))!=-1){ fos.write(buffer,0,line); localsize+=line; System.out.println(localsize+"/"+fileSize); } System.out.println("下载完成"); fos.close(); in.close();
以下是我的demo
http://download.csdn.net/download/a708959817/9967149
阅读全文
1 0
- (Android网络1)HttpURLConnection
- android 网络连接1:HttpURLConnection
- Android HttpURLConnection网络通信
- android HttpURLConnection网络访问
- Android网络编程---HttpURLConnection
- HttpURLConnection----Android网络编程
- android 用HttpURLConnection读网络
- Android网络HttpURLConnection和HttpClient
- android网络通信之HttpUrlConnection
- Android网络编程之HttpURLConnection
- Android的网络连接HttpUrlConnection
- Android 网络通信之 HttpURLConnection
- Android网络开发之HttpURLConnection
- Android网络编程之HttpURLConnection
- Android网络HttpURLConnection和HttpClient
- Android网络通信之HttpURLConnection
- android HttpURLConnection网络请求数据
- android 请求网络数据 HttpURLConnection
- 中国微生物组计划—农作物微生物组:跨越转化临界点的现代生物技术
- UEditor前端配置项说明
- PAT 乙级练习题 1001. 害死人不偿命的(3n+1)猜想 (15)
- HDU
- 打造博客专属域名
- (Android网络1)HttpURLConnection
- PAT 乙级练习题 1002. 写出这个数 (20)
- Valid Parentheses
- Eclipse 安装反编译插件Compiler
- shell 完成快速排序
- UEditor后端配置项说明
- 题目169-素数
- 配置依赖反射设置注入
- 四边形优化DP CCF 201612-04权压缩编码