Java中以POST的方式发送和接收数据

来源:互联网 发布:淘宝卖家新手入门 编辑:程序博客网 时间:2024/05/18 09:47

发送数据方法:

 

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) {}}