gpt4 book ai didi

java - 如何使用 NameValuePair 将数组值发送到 servlet?

转载 作者:行者123 更新时间:2023-12-01 23:59:21 25 4
gpt4 key购买 nike

我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com