【问题标题】:Servlet not returning JSON to androidServlet 未将 JSON 返回到 android
【发布时间】:2015-02-21 07:18:21
【问题描述】:

我正在尝试将图像从 android 客户端发送到 servlet。我正在使用 JSON 在 servlet 中发送编码图像和解码。

当我在 Eclipse 中运行 servlet 时,我在 tomcat 服务器控制台上得到“null”。当我尝试将 printf 语句用于测试时,给出了相同的响应。

我的servlet cose是:

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
{
    try
    {
    res.setContentType("application/json");
    res.setHeader("Cache-Control", "nocache");
    res.setCharacterEncoding("utf-8");
    PrintWriter out = res.getWriter();

    JSONObject json = new JSONObject();

    String jsonString = json.getString("image");

    byte[] decodedString = Base64.decodeBase64(jsonString.getBytes());//, Base64.DEFAULT);

    FileOutputStream fos = new FileOutputStream("C:\\Users\\OWNER\\Desktop\\image.jpg");
    try {
        fos.write(decodedString);
    }
    finally {
        fos.close();
    }        

    // finally output the JSON with 1 for success
    JSONObject response=new JSONObject();
    out.println(response.put("result", 1).toString());
    }
    catch(Exception e){e.printStackTrace();}

}

android代码是:

class ImageUploadTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... unsued) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(URL);

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                HttpEntity res;

                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                // Compress to jpg and convert to byte[]:

                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                String imgData= Base64.encodeToString(data, Base64.DEFAULT);
                String img=imgData.replace("\n", "%20");

                //add fields in JSON:

                JSONObject jsonObject= new JSONObject();

                jsonObject.put("img",data);

                httpPost.setEntity(new ByteArrayEntity(jsonObject.toString().getBytes("UTF8")));

                HttpResponse response = httpClient.execute(httpPost);

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                String sResponse = reader.readLine();
                return sResponse;

            } catch (Exception e) {
                if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(),
                        e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }

        }


        @Override
        protected void onPostExecute(String sResponse) {
            try {
                if (dialog.isShowing())
                    dialog.dismiss();

                if (sResponse != null) {
                    JSONObject JResponse = new JSONObject(sResponse);
                    int success = JResponse.getInt("result");
                    if (success == 1) {
Toast.makeText(getApplicationContext(),

                                    "Photo uploaded successfully",
                                    Toast.LENGTH_SHORT).show();
                            caption.setText("");

                    } else {
                       Toast.makeText(getApplicationContext(), "Error",
                                Toast.LENGTH_LONG).show();
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
    }

web.xml:

<servlet>
<servlet-name>q</servlet-name>
<servlet-class>Server1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>q</servlet-name>
<url-pattern>/P4</url-pattern>
</servlet-mapping>

在安卓设备上启动应用程序后,按下上传按钮时,没有响应。在 tomcat 服务器上,我得到“null”。

我怎样才能做到这一点?谢谢!

【问题讨论】:

  • 按下上传按钮后,您是否在服务器上收到out.println(response.put("result", 1).toString())
  • @ρяσѕρєяK 我在服务器上得到的唯一响应是'null'。
  • 你能告诉我你称之为移动端的url吗?
  • @DigveshPatel URL是:192.168.1.104:8080/vaishnavee/P4这里P4映射到上面的servlet代码
  • 服务器???意味着给我完整的网址

标签: android json servlets


【解决方案1】:

如果您的客户端工作正常:

您应该根据请求创建 json 对象:

    BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));

    String jsonStr = "";
    if(br != null)
        jsonStr = br.readLine();
    JSONObject json = new JSONObject(jsonStr); 

使用img 代替image

String jsonString = json.getString("img");

编辑:首先要调试您的程序,请编写一个简单的示例:一个只返回简单 json 结果的 servlet。通过 firebug 和 firefox 测试这个 servlet。然后添加一个只调用这个 servlet 的 android 程序。如果这个简单的程序运行正常,那么逐步添加程序的其他方面,并在每一步测试您的程序。

【讨论】:

  • 未定义的 fromObject() 方法
  • @vaishnavee:不客气。我已经更新了我的答案。
  • @vaishnavee:不要尝试,等等。
  • @vaishnavee:你在使用 org.json 库吗?
  • 感谢您的帮助。我从 servlet 转向使用 jersey 的 Web 服务,并获得了一些教程的帮助。现在我的应用程序工作正常。谢谢!
猜你喜欢
  • 2018-01-07
  • 2012-03-27
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 2015-02-27
相关资源
最近更新 更多