我想通過一個java應用程序發送一個字符串,它是一個json,它不會在servlet中獲得這個json,我該怎麼辦,誰能幫助我? 這是我的servlet代碼:如何通過java應用程序將數據傳輸到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();
你的代碼永遠不會發送JSON。將它發送到連接的輸出流,然後精確地告訴你發生了什麼。 –
我hava嘗試輸出流像thisOutputStream out = urlconn.getOutputStream(); \t \t \t out.write(json.getBytes(「UTF-8」)); \t \t \t out.flush(); \t \t \t out.close();但不起作用 –
「它不起作用」對問題描述很差。什麼不行?它怎麼不工作?如果你得到一個異常,堆棧跟蹤是什麼?當你去看醫生時,你不只是說「我生病了,疼」。你描述症狀,你的感受,在哪裏。同樣在這裏。 –