将JSON数据发送到servlet导致空字符串

时间:2016-09-13 14:51:22

标签: java json servlets

我找到的每个代码都搜索并测试了2天,绝对没有运气。 我将json文件发送到servlet,我非常确定数据是否正确发送;由于某种原因,我无法从请求的输入流中获取它们。

这里是数据发送者的代码:

{
...
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());

    Gson gson = new Gson();
    String jsonString = gson.toJson(<POJO_to_send>).toString();
    wr.writeBytes(URLEncoder.encode(jsonString,"UTF-8"));

    wr.flush();
    wr.close();        

    String responseMessage = con.getResponseMessage();
...
}

来自servlet的代码:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String s = "";
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));

    while((s=br.readLine())!=null) {
         s = br.readLine();
         sb.append(s);
    }

    String jsonString = sb.toString();
    if (jsonString != null) {
        jsonString = br.readLine();
    }else{
        IOException ioex = new IOException("Error reading data.");
        throw(ioex);
    }   
}

由于某些原因我还没有找到,sb.toString()会产生空值,因为sb是一个空字符串。从调试我发现请求的输入流的buf值似乎不为空(至少在其中有一些字节数据,在我看来它们与发送者的数据输出写入器相同)

你有没有看到我错过的一些错误?我可以在数据到达servlet之前检查数据(可能编码在某处失败)吗?

任何建议/想法?

谢谢

3 个答案:

答案 0 :(得分:0)

正如 stdunbar 所说,没有写入OutputStream。感谢 joop-eggen 提供所有建议。

请尝试以下方式发送:

   {
    ...
        Gson gson = new Gson();
        DataOutputStream wr = new DataOutputStream(resp.getOutputStream());
        String jsonString = gson.toJson(<POJO_to_send>).toString();

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty( "Content-Length", String.valueOf(jsonString.length()));
        con.setDoOutput(true);

        wr.writeBytes(jsonString);
        wr.flush();
        wr.close();     

        String responseMessage = con.getResponseMessage();
    ...
    }

获得:

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
    String sb = new String(); 
          try {
            String line = "";
            while ((line = br.readLine()) != null)
             sb += line;
          } catch (Exception e) { 
            e.printStackTrace();
          }

      String jsonString = sb;
}

答案 1 :(得分:0)

DataOutputStream是反作用的。在没有传递内容类型和字符集的情况下,代码变为:

对于POST,我们需要一个HTML表单参数,比如json=...。 不幸的是,发布表单数据需要更多格式化,所以让我们试试吧。

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
con.connect(); // .............
OutputStream out = con.getOutputStream();

Gson gson = new Gson();
String jsonString = gson.toJson(<POJO_to_send>).toString() + "\r\n";
out.write(jsonString.getBytes(StandardCharsets.UTF_8));
out.close();

String responseMessage = con.getResponseMessage();

在请求方法POST的每种情况下,必须在servlet中使用doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    BufferedReader br = new BufferedReader(
        new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));

    StringBuilder sb = new StringBuilder();
    String s;
    while ((s = br.readLine()) != null) {
         sb.append(s).append("\n");
    }

    String jsonString = sb.toString();
}

答案 2 :(得分:0)

如果您使用tomcat或其他服务器的相关属性,则必须更新server.xml中的属性maxpostSize=""