Servlet没有将JSON返回给android

时间:2014-12-23 06:50:31

标签: android json servlets

我正在尝试将图像从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>

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

我该如何使这项工作?谢谢!

1 个答案:

答案 0 :(得分: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程序。如果这个简单的程序正常工作,那么一步一步地添加程序的其他方面,并在每一步测试你的程序。