接收到客户端的Post数据后,服务器端响应doPost方法,可以实现对接收到的数据处理,并通过PrintWriter out = response.getWriter()向客户端发送数据。
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("---------post-------------");
String name = new String(request.getParameter("name").getBytes(
"iso-8859-1"), "UTF-8");
String age = request.getParameter("age");
String classes = new String(request.getParameter("classes").getBytes(
"iso-8859-1"), "UTF-8");
System.out.println("--------" + name + age + classes + "---------");
response.setContentType("text/xml; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("POST method");
out.print("name=" + name + ",age=" + age + ",classes=" + classes);
out.flush();
out.close();
}
客户端的NetTool.java中的sendPostRequest方法返回的是服务器端out.print()中的内容:
public static String sendPostRequest(String urlPath,
Map<String, String> params, String encoding) throws Exception {
StringBuilder sb = new StringBuilder();
// 如果参数不为空
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
// Post方式提交参数的话,不能省略内容类型与长度
sb.append(entry.getKey()).append('=').append(
URLEncoder.encode(entry.getValue(), encoding)).append(
'&');
}
sb.deleteCharAt(sb.length() - 1);
}
// 得到实体的二进制数据
byte[] entitydata = sb.toString().getBytes();
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(TIMEOUT);
// 如果通过post提交数据,必须设置允许对外输出数据
conn.setDoOutput(true);
// 这里只设置内容类型与内容长度的头字段
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Charset", encoding);
conn.setRequestProperty("Content-Length", String
.valueOf(entitydata.length));
OutputStream outStream = conn.getOutputStream();
// 把实体数据写入是输出流
outStream.write(entitydata);
// 内存中的数据刷入
outStream.flush();
outStream.close();
// 如果请求响应码是200,则表示成功
if (conn.getResponseCode() == 200) {
// 获得服务器响应的数据
BufferedReader in = new BufferedReader(new InputStreamReader(conn
.getInputStream(), encoding));
// 数据
String retData = null;
String responseData = "";
while ((retData = in.readLine()) != null) {
responseData += retData;
}
in.close();
return responseData;
}
return "sendText error!";
}
是通过conn.getInputStream()获得服务器端输出的内容