【问题标题】:Getting response headers with Java, encoding issue使用 Java 获取响应标头,编码问题
【发布时间】:2017-01-16 15:51:01
【问题描述】:

我正在使用 Webharvest 从网站下载文件并取其原始名称。

我正在使用的 Java 代码是:

import org.apache.commons.httpclient.Header;
            import org.apache.commons.httpclient.HttpClient;
            import org.apache.commons.httpclient.HttpStatus;
            import org.apache.commons.httpclient.Header;
            import org.apache.commons.httpclient.methods.GetMethod; 

            HttpClient client = new HttpClient();

            BufferedReader br = null;
            StringBuffer result = new StringBuffer();
            String attachName;

            GetMethod method = new GetMethod(attachmentLink.toString());

            int returnCode; 
            returnCode = client.executeMethod(method);
            Header[] headers = method.getResponseHeader("Content-Disposition");
            attachName = headers[0].getValue();
            attachName = new String(attachName.getBytes());

webharvest 中的结果是:

附件; filename="Resoluci�n sobre Mesas de Contrataci�n.pdf"

我不能让它接受这封信

ó

在将标头 Content-Disposition 的值放入变量 attachName 后,我也尝试对其进行解码,但没有成功:

String attachNamef = URLEncoder.encode(attachName, "ISO-8859-1"); 
                      attachNamef = URLEncoder.decode(attachNamef, "UTF-8");

我能够确定响应字符集是:ISO-8859-1

method.getResponseCharSet()

附:当我在 Firefox Firebug 中看到标题时 - 值没问题: 内容处置

附件; filename="Resolución sobre Mesas de Contratación.pdf"

【问题讨论】:

  • 请注意,响应字符集是指有效负载,而不是标头字段。另请注意,您似乎使用的是非常过时的 HTTP 组件版本。最后,服务器响应无效;此处不允许使用非 ASCII 字符;请参阅 RFC 6266。

标签: java http encoding response webharvest


【解决方案1】:

Apache HttpClient 不支持 HTTP 标头中的非 ascii 字符。 Taken from documentation:

HTTP 请求或响应的标头必须采用 US-ASCII 格式。不能在请求或响应的标头中使用非 US-ASCII 字符。但是,通常这不是问题,因为 HTTP 标头旨在促进数据传输,而不是实际传输数据本身。 然而,cookie 是一个例外。由于 cookie 作为 HTTP 标头传输,因此它们仅限于 US-ASCII 字符集。有关详细信息,请参阅 Cookie 指南。

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多