Android AsyncHttpClient - 下载文件时"Content-Type not allowed!"



我使用的是http://loopj.com/android-async-http/并让它调用web服务来检索JSON响应。我现在正在尝试调用一个web服务,该服务通过HTTP将文件流式传输回客户端。因此,我使用BinaryHttpResponseHandler来捕获返回的byte[]数据。然而,每次我尝试调用该方法时,它都会失败,并且在检查Throwable对象时,异常为"org.apache.http.client.HttpResponseException:不允许使用内容类型!"!"。

我试着根据文档指定一个允许的内容类型列表,但这并没有什么不同。我主要是流式PDF,但理想情况下,我不想指定内容类型列表,我希望能够下载任何文件类型。我使用的代码如下:

AsyncHttpClient httpClient = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "application/pdf", "image/png", "image/jpeg" };
httpClient.get(myWebServiceURL, new BinaryHttpResponseHandler(allowedContentTypes) {
    @Override
    public void onSuccess(byte[] binaryData) {
        // ....
    }
    @Override
    public void onFailure(Throwable error, byte[] binaryData) {
        // ....
        Log.e("Download-onFailure", error.getMessage()); 
    }
});

我也尝试过不指定任何内容类型,只使用:

new BinaryHttpResponseHandler() 

但这并没有什么区别。

忽略我,BinaryHttpResponseHandler没有任何问题。我从web服务中提取的文件是PDF、JPG、PNG等,所以我允许内容类型为application/PDF、images/jpeg、images/PNG。然而,我使用WireShark检查了返回的HTTP响应标头,发现内容类型实际上是"text/html;charset=ISO-8859-1'。一旦我将其添加到允许的内容类型中,一切都很好。

添加以下方法以查看"不接受"的内容

public void sendResponseMessage(HttpResponse response) {
    System.out.println(response.getHeaders("Content-Type")[0].getValue());
}

对我来说,结果是"image/png;charset=UTF-8"

然后添加它;)

我发现BinaryHttpResponseHandler.java中的代码如下:

boolean foundAllowedContentType = false;
for(String anAllowedContentType : mAllowedContentTypes) {
    if(anAllowedContentType.equals(contentTypeHeader.getValue())) {
        foundAllowedContentType = true;
    }
}

似乎你必须列出你想要接收的所有类型。

您可以准确地检查web服务返回的文件类型。只需覆盖BinaryHttpResponseHandler中的onFailure,如下所示:

@Override 
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) 
{ 
    Log.e(TAG, "onFailure!"+ error.getMessage());
    for (Header header : headers)
    {
        Log.i(TAG, header.getName()+" / "+header.getValue());
    }
}   

希望这能帮助

尝试添加*/*

String[] allowedContentTypes = new String[] { "*/*", "application/pdf", "image/png", "image/jpeg" };

添加"application/octet stream"作为允许的类型对我有效!

干杯

我遇到了同样的问题。我查了来源。URL在之后

https://github.com/loopj/android-async-http/blob/master/library/src/main/java/com/loopj/android/http/BinaryHttpResponseHandler.java

android async只支持两种内容类型:"images/jpeg"one_answers"images/png"

我认为如果你需要其他类型的内容,你需要覆盖类。

就这样做:

String[] allowedContentTypes = new String[] { "image/jpeg;charset=utf-8", "image/jpeg;charset=utf-8" };

没关系。

也有同样的问题。经过一段时间的挖掘,想出了在内容类型末尾添加".*"的解决方案,以防止指定实际内容类型和字符集的所有组合:

String[] allowedContentTypes = new String[] { "application/pdf.*", "image/png.*", "image/jpeg.*" };

相关内容

最新更新