Java中以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) {

			}
		}


 

展开阅读全文

没有更多推荐了,返回首页