我想通过一个java应用程序发送一个json字符串,在servlet中没有得到这个json,我该怎么办,谁能帮助我?这是我的 servlet 代码:
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
BufferedInputStream in = new BufferedInputStream(req.getInputStream());
byte[] data = null;
byte[] bts = new byte[1024];
int index;
while ((index = in.read(bts)) >= 0) {
if (data == null) {
data = new byte[index];
System.arraycopy(bts, 0, data, 0, index);
}
else {
byte[] tmp = data;
data = new byte[tmp.length + index];
System.arraycopy(tmp, 0, data, 0, tmp.length);
System.arraycopy(bts, 0, data, tmp.length, index);
}
}
String json = new String(data);
System.out.print(json);
}
这是我的java应用程序:
String _url = "http://localhost:8080/jsf/test";
URL url = null;
HttpURLConnection urlconn = null;
String json = URLEncoder.encode(JSONObject.fromObject(req)
.toString(), "UTF-8");
url = new URL(_url);
urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestMethod("POST");
urlconn.setDoOutput(true);
urlconn.setDoInput(true);
OutputStream out = urlconn.getOutputStream();
out.write(json.getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlconn.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1) {
sb.append((char) ch);
}
System.out.println(sb);
rd.close();