我正在尝试将 boolean 值数组发送到 servlet。 这就是我到目前为止所做的,我很困惑:
HttpClient client = new DefaultHttpClient();
String postURL = "http://APP_NAME.appspot.com/listenforrestclient";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (int i=0; i<arrBool.length; i++) {
arrBool[i] = r.nextBoolean();
String[] user = {"","","","","",""};
if (arrBool[i] == true) {
params.add(new BasicNameValuePair("user[i]", arrBool.toString()));
}
else if (arrBool[i] == false) {
params.add(new BasicNameValuePair("user[i]", arrBool.toString()));
}
}
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
System.out.printf("RESPONSE: ", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
我尝试只执行 user[i], "user[i]", user.还是没找到。
在 servlet 上我有:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
{
resp.setContentType("text/plain");
for (int i=0; i<mmaa.length; i++) {
mmaa = req.getParameterValues("user");
resp.getWriter().println(mmaa[i]);
}
}
网上查了很多,没有找到合适的。如果有人能帮助我解决这个问题,我将非常感激。
谢谢
最佳答案
您有params.add(new BasicNameValuePair("user[i]", arrBool.toString()));
但是你的 key 是字符串“user[i]”
。使用 String.format("user[%d]", i)
代替。
所以,改变一下
params.add(new BasicNameValuePair("user[i]", arrBool.toString()));
至
params.add(new BasicNameValuePair(String.format("user[%d]", i), arrBool.toString()));
在 servlet 中,您可以通过执行以下操作来获取参数值:
for(int i = 0; i < ...){
String value = request.getParameter(String.format("user[%d]", i);
//process value
}
关于java - 如何使用 NameValuePair 将数组值发送到 servlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15128417/