我有一个发送回 JSON 对象的 Servlet,我想在另一个 Java 项目中使用此 Servlet。我有这个方法可以得到结果:
public JSONArray getSQL(String aServletURL)
{
JSONArray toReturn = null;
String returnString = "";
try
{
URL myUrl = new URL(aServletURL);
URLConnection conn = myUrl.openConnection();
conn.setDoOutput(true);
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
String s;
while ((s = in.readLine()) != null )
returnString += s;
in.close();
toReturn = new JSONArray(returnString);
}
catch(Exception e)
{
return new JSONArray();
}
return toReturn;
}
这很有效,但我面临的问题如下: 当我同时执行多个请求时,结果会混淆,有时会得到与我发送的请求不匹配的响应。
我怀疑问题与我获取响应的方式有关:读取器从连接的 InputStream 读取字符串。
如何确保我收到一个请求 -> 一个相应的回复? 有没有更好的方法从 servlet 检索 JSON 对象?
干杯, 蒂姆
最佳答案
When I do several simultaneous requests, the results get mixed up and I sometimes get a Response that does not match the request I send.
您的 servlet 不是线程安全的。我敢打赌,您已经错误地将请求范围的数据直接或间接分配为 servlet 的实例或类变量。这是初学者常见的错误。
仔细阅读此How do servlets work? Instantiation, sessions, shared variables and multithreading并相应地修复您的 servlet 代码。问题不在目前显示的 URLConnection
代码中,尽管它表明您在 两者 doGet()
中执行完全相同的工作和 doPost()
,这反过来又已经让人了解 servlet 的设计方式了。
关于java - 发送回 JSON : Confusion on reception 的 Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8847995/