httpURLConnection-网络请求的两种方式-get请求和post请求
来源:互联网 发布:河北省网络行政学院 编辑:程序博客网 时间:2024/06/05 11:36
GET请求
/** * 从网络获取json数据,(String byte[}) * @param path * @return */ public static String getJsonByInternet(String path){ try { URL url = new URL(path.trim()); //打开连接 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if(200 == urlConnection.getResponseCode()){ //得到输入流 InputStream is =urlConnection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while(-1 != (len = is.read(buffer))){ baos.write(buffer,0,len); baos.flush(); } return baos.toString("utf-8"); } } catch (IOException e) { e.printStackTrace(); } return null; }
POST请求
//获取其他页面的数据 /** * POST请求获取数据 */ public static String postDownloadJson(String path,String post){ URL url = null; try { url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式 // conn.setConnectTimeout(10000);//连接超时 单位毫秒 // conn.setReadTimeout(2000);//读取超时 单位毫秒 // 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); // 发送请求参数 printWriter.write(post);//post的参数 xx=xx&yy=yy // flush输出流的缓冲 printWriter.flush(); //开始获取数据 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] arr = new byte[1024]; while((len=bis.read(arr))!= -1){ bos.write(arr,0,len); bos.flush(); } bos.close(); return bos.toString("utf-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
阅读全文
0 0
- httpURLConnection-网络请求的两种方式-get请求和post请求
- httpURLConnection-网络请求的两种方式-get请求和post请求
- HttpURLConnection的GET和POST请求方式
- HttpUrlConnection的GET请求和POST请求
- httpurlconnection的Get请求和Post请求
- HttpUrlConnection两种请求数据的方式get和post提交数据
- iOS 网络请求数据两种请求方式GET,POST
- HttpURLConnection:POST和GET 网络请求
- 使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据
- HttpURLConnection,get,post,网络请求
- HttpURLConnection 网络请求 get post
- HttpUrlConnection和HttpClient两种方式获取GET和POST请求
- 网络请求----HttpURLConnection的get,post和图片加载
- GET和POST两种请求方式的区别
- GET和POST两种请求方式的区别
- HttpUrlConnection post和get请求
- HttpURLconnection/get和post请求
- httpUrlConnection用于post请求和get请求
- python3 [爬虫入门实战]爬虫之scrapy安装与配置教程
- 分布式消息队列RocketMQ与Kafka架构上的巨大差异之1 -- 为什么RocketMQ要去除ZK依赖?
- 【PAT】【Advanced Level】1062. Talent and Virtue (25)
- [SDUT](2144)图结构练习——最小生成树 ---最小生成树(图)
- NIO的一些坑
- httpURLConnection-网络请求的两种方式-get请求和post请求
- 摆花
- Python: 创建空的list,以及append用法
- TCP协议原理详解
- 数据离散化模板(用STL实现)
- 谈谈谷歌word2vec的原理
- python使用 UTF-8编码
- 机翼的翼型和升力
- 洛谷p2239 螺旋矩阵