Java中以POST的方式发送和接收数据
2012-12-12 15:12
375 查看
发送数据方法:
处理post之后返回的数据:
接收Post传的数据:
URL url = null; String inputLine = null; HttpURLConnection httpurlconnection = null; try { url = new URL(urladdr); httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setRequestProperty("content-type","text/html"); httpurlconnection.setRequestMethod("POST"); httpurlconnection.setDoOutput(true); httpurlconnection.setDoInput(true); httpurlconnection.setUseCaches(false); httpurlconnection.getOutputStream().write(param.getBytes()); httpurlconnection.getOutputStream().flush(); httpurlconnection.getOutputStream().close(); int code = httpurlconnection.getResponseCode(); inputLine = readContents(httpurlconnection); } catch (Exception e) { e.printStackTrace(); } finally { if (httpurlconnection != null) httpurlconnection.disconnect(); } return inputLine;
处理post之后返回的数据:
private String readContents(HttpURLConnection httpurlconnection) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(httpurlconnection .getInputStream())); StringBuffer temp = new StringBuffer(); String inputLine = in.readLine(); while (inputLine != null) { temp.append(inputLine); inputLine = in.readLine(); } return temp.toString(); } catch (IOException e) { e.printStackTrace(); } finally { in.close(); } return null; }
接收Post传的数据:
response.setContentType("text/html");// 注意加上 java.io.BufferedReader reader = null; try { reader = request.getReader();// 获得字符流 StringBuffer content = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { content.append(line + "\r\n"); } result = content.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { reader.close(); reader = null; } catch (Exception e) { } }
相关文章推荐
- httpclient使用post方式发送json数据,以及服务端的接收
- express 4.x req.query(get方式) req.body(post方式) 接收浏览器发送过来的数据
- Java发起GET/POST请求,接收或发送URL中的数据的问题
- Java模块 -- Http发送post数据文件,服务端Servlet接收,保存至本地
- java通过post方式发送接收xml信息
- java后台接收android客户端通过http方式发送的数据
- java通过post方式发送接收xml信息
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
- Java基础知识强化之网络编程笔记03:UDP之UDP协议发送数据 和 接收数据
- struts2 数据传输问题---“POST方式提交数据量过大,在后台接收不到数据”问题的解决
- Java Socket 服务端发送数据 客户端接收数据
- HttpWebRequest Post 方式发送 XML数据
- Asp.net XMLHTTP 基类 (GET,Post发送和接收数据)
- java Post 发送数据乱码问题
- PHP接收POST数据方式
- java 通过发送json,post请求,返回json数据
- 后端接收不到AngularJs中$http.post发送的数据原因分析及解决办法
- 谈谈Java利用原始HttpURLConnection发送POST数据
- domino代理通过Request_Content域接收extjs以post方式提交的数据
- 用 AFNetworking 通过 POST 方式发送数据