检查HttpResponse是否包含字符串或null或图像

时间:2013-06-20 08:45:24

标签: android httpresponse

如果服务器没有返回图像,我想将imgData发送为null。但是使用此代码它永远不会返回null。我需要检查HttpResponse是否包含null或image或者当我发送响应时的错误消息如果图像存在,则以字节数组的形式发送,如果不存在则为空,如果发生错误,则发送错误消息。

public static byte[] getCommentImage(final int commentId) {
    byte[] imgData = null;
    HttpResponse res= null;
    try {
        res = $.get(COMMENT_IMAGE_URL, new Object[] {"comment_id", commentId });
        HttpEntity resEntity = res.getEntity();
        imgData = EntityUtils.toByteArray(resEntity);
        Log.d("getCommentImage API",imgData+" ");
    } catch (Exception e) {
       e.printStackTrace();
    }
   return imgData;
   }

1 个答案:

答案 0 :(得分:0)

HTTP响应通常包含声明内容类型的标头。 对于图像“image / jpeg”或“image / png”,“String”(或HTML页面)通常是内容类型“text / html”。

resEntity.getContentType().getValue();

此外,您拥有状态/结果代码:

res.getStatusLine().getStatusCode();

我假设结果代码是!= 200(HTTP_OK),以防你得到一个空值。

相关问题