2017-01-16 76 views
0

我正在使用Webharvest從網站下載文件並採用其原始名稱。使用Java獲取響應標頭,編碼問題

,我有工作的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結果是:

附件;文件名= 「Resolucin自我臺地德Contratacin.pdf」

我不能讓它以信

ó

我得到了標題內容的價值後, - 分配到變量attachName,我也試着解碼它,但沒有運氣:

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

我能夠解決rmine表示響應字符集是:ISO-8859-1

method.getResponseCharSet() 

P.S.當我在Firefox Firebug中看到標題時 - 值正常: 內容處置

附件; filename =「Resoluciónsobre Mesas deContratación.pdf」

+0

請注意,響應字符集指的是有效負載,而不是頭字段。 另請注意,您似乎正在使用一個非常過時的HTTP組件版本。 最後,服務器響應無效;這裏不允許使用非ASCII字符;請參閱RFC 6266。 –

回答

2

Apache HttpClient不支持HTTP標頭中的非ASCII字符。 Taken from documentation

HTTP請求或響應的標頭必須採用US-ASCII格式。在請求或響應的標題中不能使用非US-ASCII字符。然而,通常這不是問題,因爲HTTP標頭設計用於促進數據傳輸,而不是實際傳輸數據本身。 但是有一個例外是cookies。由於Cookie被轉換爲HTTP標題,因此它們僅限於US-ASCII字符集。請參閱Cookie指南瞭解更多信息。