首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Servlet不向android返回JSON

Servlet不向android返回JSON
EN

Stack Overflow用户
提问于 2014-12-23 14:50:31
回答 1查看 159关注 0票数 0

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

当我在eclipse中运行servlet时,我在tomcat服务器控制台上得到'null‘。当我尝试将printf语句用于测试时,也会得到相同的响应。

我的servlet代码是:

代码语言:javascript
运行
复制
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代码是:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<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设备上启动app后,按下upload按钮,没有响应。在tomcat服务器上,我得到了'null‘。

我怎么才能让它工作呢?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2014-12-23 21:02:33

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

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

代码语言:javascript
运行
复制
    BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));

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

使用img而不是image

代码语言:javascript
运行
复制
String jsonString = json.getString("img");

servlet编辑servlet:要调试您的程序,首先要编写一个简单的示例:一个,它只返回一个简单的结果。使用firebug和firefox测试此servlet。然后添加一个调用此servlet的android程序。如果这个简单的程序工作正常,那么一步一步地添加程序的其他方面,并在每一步测试您的程序。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27615430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档