Android_HttpURLConnection_Get和Post请求 小咪咪 2022-08-19 00:26 146阅读 0赞 版权声明:本文为原创文章,未经博主允许不得转载。http://blog.csdn.net/zimo2013 目录[(?)][Link 1][\[-\]][Link 1] 1. [HttpURLConnection实现步骤][HttpURLConnection] 2. [GZIP压缩][GZIP] 3. [简单应用][Link 2] 1. [1get请求][1get] 2. [2post表单提交][2post] 3. [3post文件上传][3post] **[本博文为子墨原创,转载请注明出处!][Link 3]** ***[http://blog.csdn.net/zimo2013/article/details/9469543][http_blog.csdn.net_zimo2013_article_details_9469543]*** [**关于HttpClient用法**][HttpClient] # 1.HttpURLConnection实现步骤 # > (1).得到HttpURLConnection对象,通过调用URL.openConnection()方法得到该对象 > (2).设置请求头属性,比如数据类型,数据长度等等 > (3).可选的操作 setDoOutput(true),默认为false无法向外写入数据!setDoInput(true),一般不用设置默认为true > (4).浏览器向服务器发送的数据,比如post提交form表单或者像服务器发送一个文件 > (5).浏览器读取服务器发来的相应,包括servlet写进response的头数据(content-type及content-length等等),body数据 > (6).调用HttpURLConnection的disconnect()方法, 即设置 http.keepAlive = false;释放资源 > # 2.GZIP压缩 # > 对于文本数据,特别是json数据或者html网页数据,最好使用gzip进行压缩,理论上文本数据可以压缩为原来的1/3,效果很明显,压缩之后应该使用gzip流进行解压缩! > > **\[java\]** [ view plain][Link 1] [copy][Link 1] > > 1. conn.setRequestProperty("Accept-Encoding", "gzip"); //设置头参数 > 2. > 3. InputStream is = new BufferedInputStream(conn.getInputStream()); > 4. String encoding = conn.getContentEncoding(); > 5. if(encoding!=null && encoding.contains("gzip"))\{ //首先判断服务器返回的数据是否支持gzip压缩, > 6. is = new GZIPInputStream(is); //如果支持则应该使用GZIPInputStream解压,否则会出现乱码无效数据 > 7. \} # 3.简单应用 # ## (1).get请求 ## **\[java\]** [ view plain][Link 1] [copy][Link 1] 1. public static void get() \{ 2. HttpURLConnection conn = null; 3. try \{ 4. URL url = new URL("http://127.0.0.1:8080/Day18/servlet/UploadTest"); 5. //1.得到HttpURLConnection实例化对象 6. conn = (HttpURLConnection) url.openConnection(); 7. //2.设置请求信息(请求方式... ...) 8. //设置请求方式和响应时间 9. conn.setRequestMethod("GET"); 10. //conn.setRequestProperty("encoding","UTF-8"); //可以指定编码 11. conn.setConnectTimeout(5000); 12. //不使用缓存 13. conn.setUseCaches(false); 14. //3.读取相应 15. if (conn.getResponseCode() == 200) \{ 16. //先将服务器得到的流对象 包装 存入缓冲区,忽略了正在缓冲时间 17. InputStream in = new BufferedInputStream(conn.getInputStream()); 18. // 得到servlet写入的头信息,response.setHeader("year", "2013"); 19. String year = conn.getHeaderField("year"); 20. System.out.println("year="\+year); 21. byte\[\] bytes = readFromInput(in); //封装的一个方法,通过指定的输入流得到其字节数据 22. System.out.println(new String(bytes, "utf-8")); 23. System.out.println("\[浏览器\]成功!"); 24. \} else \{ 25. System.out.println("请求失败!"); 26. \} 27. \} catch (Exception e) \{ 28. e.printStackTrace(); 29. \} finally \{ 30. //4.释放资源 31. if (conn != null) \{ 32. //关闭连接 即设置 http.keepAlive = false; 33. conn.disconnect(); 34. \} 35. \} 36. \} ## (2).post表单提交 ## **\[java\]** [ view plain][Link 1] [copy][Link 1] 1. /\*\* 2. \* post请求方式,完成form表单的提交 3. \*/ 4. public static void post() \{ 5. HttpURLConnection conn = null; 6. try \{ 7. URL url = new URL("http://127.0.0.1:8080/Day18/servlet/Logining"); 8. String para = new String("username=admin&password=admin"); 9. //1.得到HttpURLConnection实例化对象 10. conn = (HttpURLConnection) url.openConnection(); 11. //2.设置请求方式 12. conn.setRequestMethod("POST"); 13. //3.设置post提交内容的类型和长度 14. /\* 15. \* 只有设置contentType为application/x-www-form-urlencoded, 16. \* servlet就可以直接使用request.getParameter("username");直接得到所需要信息 17. \*/ 18. conn.setRequestProperty("contentType","application/x-www-form-urlencoded"); 19. conn.setRequestProperty("Content-Length", String.valueOf(para.getBytes().length)); 20. //默认为false 21. conn.setDoOutput(true); 22. //4.向服务器写入数据 23. conn.getOutputStream().write(para.getBytes()); 24. //5.得到服务器相应 25. if (conn.getResponseCode() == 200) \{ 26. System.out.println("服务器已经收到表单数据!"); 27. \} else \{ 28. System.out.println("请求失败!"); 29. \} 30. \} catch (Exception e) \{ 31. e.printStackTrace(); 32. \} finally \{ 33. //6.释放资源 34. if (conn != null) \{ 35. //关闭连接 即设置 http.keepAlive = false; 36. conn.disconnect(); 37. \} 38. \} 39. \} ## (3).post文件上传 ## **\[java\]** [ view plain][Link 1] [copy][Link 1] 1. /\*\* 2. \* post方式,完成文件的上传 3. \*/ 4. private static void uploadFile() \{ 5. HttpURLConnection conn = null; 6. OutputStream out = null; 7. InputStream in = null; 8. FileInputStream fin = null; 9. String filePath = "c:\\\\android帮助文档.rar"; 10. try \{ 11. fin = new FileInputStream(filePath); 12. //1.得到HttpURLConnection实例化对象 13. conn = (HttpURLConnection) new URL("http://127.0.0.1:8080/Day18/servlet/UploadTest").openConnection(); 14. //2.设置请求方式 15. conn.setRequestMethod("POST"); 16. conn.setDoOutput(true); 17. //不使用缓存 18. conn.setUseCaches(false); 19. //conn.setRequestProperty("Range", "bytes="+start+"-"+end);多线程请求部分数据 20. //3.设置请求头属性 21. //上传文件的类型 rard Mime-type为application/x-rar-compressed 22. conn.setRequestProperty("content-type", "application/x-rar-compressed"); 23. /\* 24. \* (1).在已知文件大小,需要上传大文件时,应该设置下面的属性,即文件长度 25. \* 当文件较小时,可以设置头信息即conn.setRequestProperty("content-length", "文件字节长度大小"); 26. \* (2).在文件大小不可知时,使用setChunkedStreamingMode(); 27. \*/ 28. conn.setFixedLengthStreamingMode(fin.available()); 29. String fileName = filePath.substring(filePath.lastIndexOf("\\\\")+1); 30. //可以将文件名称信息已头文件方式发送,在servlet中可以使用request.getHeader("filename")读取 31. conn.setRequestProperty("filename", fileName); 32. 33. //4.向服务器中发送数据 34. out = new BufferedOutputStream(conn.getOutputStream()); 35. long totalSize = fin.available(); 36. long currentSize = 0; 37. int len = -1; 38. byte\[\] bytes = new byte\[1024\*5\]; 39. while ((len = fin.read(bytes)) != -1) \{ 40. out.write(bytes); 41. currentSize += len; 42. System.out.println("已经长传:"\+(int)(currentSize\*100/(float)totalSize)+"%"); 43. \} 44. 45. System.out.println("上传成功!"); 46. \} catch (IOException e) \{ 47. e.printStackTrace(); 48. \} finally\{ 49. //5.释放相应的资源 50. if(conn != null)\{ 51. conn.disconnect(); 52. \} 53. \} 54. \} ***NOTE***:Android使用时,应该添加网络权限 **\[html\]** [ view plain][Link 1] [copy][Link 1] 1. <!-- 使用网络前,需要在项目清单文件中,加入如下权限代码 --> 2. <uses-permission android:name="android.permission.INTERNET"/> [Link 1]: http://blog.csdn.net/zimo2013/article/details/9469543# [HttpURLConnection]: http://blog.csdn.net/zimo2013/article/details/9469543#t0 [GZIP]: http://blog.csdn.net/zimo2013/article/details/9469543#t1 [Link 2]: http://blog.csdn.net/zimo2013/article/details/9469543#t2 [1get]: http://blog.csdn.net/zimo2013/article/details/9469543#t3 [2post]: http://blog.csdn.net/zimo2013/article/details/9469543#t4 [3post]: http://blog.csdn.net/zimo2013/article/details/9469543#t5 [Link 3]: http://blog.csdn.net/zimo2013 [http_blog.csdn.net_zimo2013_article_details_9469543]: http://blog.csdn.net/zimo2013/article/details/9469543 [HttpClient]: http://blog.csdn.net/zimo2013/article/details/12193427
还没有评论,来说两句吧...