本文记录的是使用Java获取Http请求中的参数,包括Get和Post请求。

获取Get请求中的参数

1
2
3
4
5
6
7
8
9
10
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

String params = req.getQueryString();

PrintWriter pw = resp.getWriter();
pw.write("you get request is success: query params = " + params);
pw.flush();
pw.close();
pw = null;
}

例如,若如下使用Get请求:

http://localhost:8080/nps?action=sendGet&params=location

那么上述代码中params的值为action=sendGet&params=location

获取Post请求中的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int contentLength = req.getContentLength();
//-1 indicate the length is not known
if (-1 != contentLength) {
byte[] requestBody = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readLength = req.getInputStream().read(requestBody, i,
contentLength - i);
//reached the end of the stream
if (-1 == readLength) {
break;
}

i += readLength;
}

String charEncoding = resp.getCharacterEncoding();
if (null == charEncoding) {
charEncoding = "UTF-8";
}
String requestContent = new String(requestBody, charEncoding);

PrintWriter pw = resp.getWriter();
pw.write("you post request is success. posted data is: "
+ requestContent);
pw.flush();
pw.close();
pw = null;
}
}

例如,若采用使用HttpURLConnection发送Get和Post请求示例一文中所示示例发送Post请求,那么上述代码的requestContent的值是UTF-8编码之后的action=get info&param=云竹字符串值.