4

我正在使用来自http://loopj.com/android-async-http/的 AsyncHttpClient 库,并让它调用 Web 服务来检索 JSON 响应。我现在正在尝试调用通过 HTTP 将文件流回客户端的 Web 服务。因此,我使用 BinaryHttpResponseHandler 来捕获返回的 byte[] 数据。但是,每次我尝试调用该方法时它都会失败,并且在检查 Throwable 对象时,异常是 'org.apache.http.client.HttpResponseException: Content-Type not allowed!'。

我已经尝试根据文档指定要允许的内容类型列表,但这并没有什么不同。我主要是流式传输 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() 

但这没有任何区别。

4

9 回答 9

6

别理我,BinaryHttpResponseHandler 没什么问题。我从网络服务中提取的文件是 PDF、JPG、PNG 等,所以我允许应用程序/pdf、图像/jpeg、图像/png 的内容类型。但是,我使用 WireShark 检查返回的 HTTP 响应标头,发现内容类型实际上是 'text/html; 字符集=ISO-8859-1'。一旦我将它添加到允许的内容类型中,一切正常。

于 2012-09-17T07:15:54.920 回答
2

添加以下方法以查看“未接受”内容

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

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

然后添加它;)

于 2013-03-04T10:11:34.023 回答
1

我发现代码BinaryHttpResponseHandler.java如下:

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

看来您必须列出您想要接收的所有类型。

于 2013-02-01T16:07:14.403 回答
1

您可以准确检查 Web 服务返回的文件类型。只需像这样覆盖onFailure你的BinaryHttpResponseHandler

@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());
    }
}   

希望这可以帮助

于 2014-01-16T11:46:07.063 回答
0

尝试添加*/*

String[] allowedContentTypes = new String[] { "*/*", "application/pdf", "image/png", "image/jpeg" };
于 2012-09-12T12:03:54.990 回答
0

添加“application/octet-stream”作为允许的类型对我有用!

干杯

于 2013-09-05T21:33:13.370 回答
0

我遇到了同样的问题。我检查了来源。网址如下

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

android-async 只支持两种Content-Type:"image/jpeg","image/png"。</p>

我想如果你需要 Content-Type 是其他的,你需要重写这个类。

于 2014-02-13T10:47:51.350 回答
0

这样做:

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

没关系。

于 2014-05-19T05:42:54.670 回答
0

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

String[] allowedContentTypes = new String[] { "application/pdf.*", "image/png.*", "image/jpeg.*" };
于 2015-03-16T04:12:21.807 回答