[英]How to Send JsonArray From Client(java or Android ) To servlet(Server)
i have to send This JsonArray With HTTP Request from client to sever and have to fetch it on to servlet page..without NameValuePair Class because my requirement is diffrent. 我必须从客户端发送带有HTTP请求的JsonArray进行服务器发送,并且必须将其提取到servlet页面上。没有NameValuePair类,因为我的要求是不同的。
any help would be appreciated. 任何帮助,将不胜感激。
hear is some code i was using to send parameters but this time its jsonArray so i cant use it 听到是我用来发送参数的一些代码,但是这次是它的jsonArray,所以我不能使用它
Map<String, String> params = new HashMap<String, String>();
params.put(Constants.NAME, name);
and then building the body. 然后建立身体。
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
and then HTTP Request. 然后是HTTP请求。
conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-forurlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
This way you can send JSON array to Server 这样,您可以将JSON数组发送到服务器
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringEntity se = new StringEntity(jsonArray.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
Servlet you can read json array like this (Use this code inside doPost method in Servlet): Servlet可以像这样读取json数组(在Servlet的doPost方法内部使用此代码):
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str;
while( (str = br.readLine()) != null ){
sb.append(str);
}
JSONArray jArr = new JSONArray(sb.toString());
Ahhhhhh...Skip bit of extra work..for those who understand my question i am posting answer ...using that method what i have mentioned in the question you can simply receive JsonArray to Servlet.. Ahhhhhh ...跳过一些额外的工作..对于那些了解我的问题的人,我正在发布答案...使用我在问题中提到的方法,您可以将JsonArray接收到Servlet。
put this into params as i mentioned 正如我提到的那样,将其置于参数中
params.put("json", jsonArray.toString());
and then for receivng in servlet.. 然后在servlet中接收。
String jsonArray=request.getParameter("json");
JSONArray jArr = new JSONArray(j.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.