Java 以post方式获取数据
来源:互联网 发布:php长连接 消息推送 编辑:程序博客网 时间:2024/05/23 00:52
之前一直是以GET的方式来请求数据,今天有个需求是以post的方式来获取数据,记录下。post 的参数有2种,一种是以string型的json格式数据,另一种是Map格式的数据
代码很简单,基本是一些流的操作和post格式设置。
代码如下:
/** * * @param url * @param isPostByJsonData 是否是String类型的json格式 * @param jsonData String类型的json格式数据 * @param params map类型的数据 */ public void getDataByPost(String url, boolean isPostByJsonData, String jsonData, Map<String, String> params){ InputStream inputStream = null; HttpURLConnection urlConnection = null; PrintWriter printWriter = null; BufferedReader bufferReader = null; InputStreamReader inputRader = null; StringBuffer contentBuffer = new StringBuffer(); try { URL url1 = new URL(url); urlConnection = (HttpURLConnection) url1.openConnection(); urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); StringBuffer stringBufParams = new StringBuffer(); if(isPostByJsonData){ stringBufParams.append(jsonData); }else { if(params != null){ for (Map.Entry<String, String> entry : params.entrySet()) { stringBufParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } stringBufParams.deleteCharAt(stringBufParams.length() - 1); } } printWriter = new PrintWriter(urlConnection.getOutputStream()); printWriter.print(stringBufParams); printWriter.flush(); int statusCode = urlConnection.getResponseCode(); if (statusCode == 200){ inputStream =urlConnection.getInputStream(); inputRader = new InputStreamReader(inputStream, "utf-8"); bufferReader = new BufferedReader(inputRader); String line = null; while (null != (line = bufferReader.readLine())) { contentBuffer.append(line); } String dd = contentBuffer.toString(); Log.e("xxx", "NetUtils dd = "+dd); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (printWriter != null) { printWriter.close(); } } catch (Exception e) { } } }
注意了,如果是Android开发,一定要在子线程中调用该方法,不然会crash.
0 0
- Java 以post方式获取数据
- 以post方式获取远程数据
- Http 以post方式获取数据
- Java中以POST的方式发送和接收数据
- Ajax以post方式提交数据
- 以Post方式发送数据采用WebClient
- 通过Http协议以Get和Post方式获取服务器端文本数据
- 使用post()方法以POST方式从服务器发送数据
- java中form以post、get方式提交数据中文乱码问题总结
- java中form以post、get方式提交数据中文乱码问题总结
- java中form以post、get方式提交数据中文乱码问题总结
- java中form以post、get方式提交数据中文乱码问题总结
- java中form以post、get方式提交数据中文乱码问题总结
- java中form以post、get方式提交数据中文乱码问题总结
- Java的HttpClient类以POST方式提交数据,目标端收到后中文乱码
- java中form以post、get方式提交数据中文乱码问题总结(转)
- 以httpclient方式提交数据—post方式
- android采用post方式获取服务器数据
- 字符集编码问题(get/post请求,tomcat有不同的处理)
- 数据库 SQL SEVER 2008 + VS2010
- 建立一个maven项目
- Linux中启动和停止jar包的运行
- 设计模式之单例设计模式
- Java 以post方式获取数据
- android基础知识汇总-Activity篇(一)
- Coprime Sequence(前后缀最大公约数)
- YOLO v2之总结篇(linux+windows)
- IIS发布网站出现“未能加载文件或程序集“System.Data.SQLite”或它的某一个依赖项。”的解决方法
- log4j配置文件的书写
- sobox弹窗控件,设置弹出窗的z-index
- arm之上的threadx OS编程之总结
- 【Java学习20170510】MySQL考试