[JAVA]HTTP请求应答作输入输出

时间:2024-01-17 10:39:20

请求(需要发送数据给别人):

URL url = new URL("需要请求的URL连接");

HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

// 以POST或GET方式通信

conn.setRequestMethod("POST");

// 设置连接超时时间

httpConnection.setConnectTimeout(this.timeOut * 1000);

// User-Agent

httpConnection.setRequestProperty("User-Agent",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");

// 不使用缓存

httpConnection.setUseCaches(false);

// 允许输入输出

httpConnection.setDoInput(true);

httpConnection.setDoOutput(true);

// Content-Type

httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// 取得输出流

BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());

// 长度以1KB为单位进行写

final int len = 1024;

// 将要输出的字符通过流做输出

String postData = "需要POST出去的数据";

byte[] outData = postData.getBytes(this.charset);

int dataLen = outData.length;

int off = 0;

// 以1KB为单位写

while (off < dataLen) {

if (len >= dataLen) {

out.write(outData, off, dataLen);

} else {

out.write(outData, off, len);

}

// 刷新缓冲区

out.flush();

off += len;

dataLen -= len;

}

// 关闭流

out.close();

// 取得应答码

int respCode = conn.getResponseCode();

// 取得返回的输入流

InputStream inputStream = conn.getInputStream();

接收(接收请求数据并应答):

// 取得输入流

InputStream in = request.getInputStream();

// 使用Reader取得输入流数据

BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

// 将Reader转成字符串

String temp;

StringBuffer sb = new StringBuffer();

while (null != (temp = br.readLine())) {

sb.append(temp);

}

// 取得最终收到的字符串

String originalReturnData = sb.toString();

// 应答给请求方的数据

String responseString = "收到请求之后应答的数据";

// 取得输出器

PrintWriter out = response.getWriter();

// 直接输出

out.println(responseString);

// 刷新输出

out.flush();

// 关闭输出

out.close();