2012-01-19 16 views
9

sto cercando di recuperare i dati da http://api.freebase.com/api/trans/raw/m/0h47Java codifica UTF-8 non impostato su URLConnection

Come si può vedere nel testo ci sono canta come questo: /ælˈdʒɪəriə/.

Quando provo ad ottenere fonte dalla pagina ricevo testo con canta come ú ecc

Finora ho provato con il seguente codice:

urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); 
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); 

Che cosa sto facendo di sbagliato?

Tutto il mio codice:

URL url = null; 
URLConnection urlConn = null; 
DataInputStream input = null; 
try { 
url = new URL("http://api.freebase.com/api/trans/raw/m/0h47"); 
} catch (MalformedURLException e) {e.printStackTrace();} 

try { 
    urlConn = url.openConnection(); 
} catch (IOException e) { e.printStackTrace(); } 
urlConn.setRequestProperty("Accept-Charset", "UTF-8"); 
urlConn.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); 

urlConn.setDoInput(true); 
urlConn.setUseCaches(false); 

StringBuffer strBseznam = new StringBuffer(); 
if (strBseznam.length() > 0) 
    strBseznam.deleteCharAt(strBseznam.length() - 1); 

try { 
    input = new DataInputStream(urlConn.getInputStream()); 
} catch (IOException e) { e.printStackTrace(); } 
String str = ""; 
StringBuffer strB = new StringBuffer(); 
strB.setLength(0); 
try { 
    while (null != ((str = input.readLine()))) 
    { 
     strB.append(str); 
    } 
    input.close(); 
} catch (IOException e) { e.printStackTrace(); } 

risposta

11

La pagina HTML è in UTF-8, e potrebbe utilizzare caratteri arabi e così via. Ma quei caratteri sopra Unicode 127 sono ancora codificati come entità numeriche come ú. Un Accept-Encoding non lo aiuterà, e non lo caricherà in quanto UTF-8 ha perfettamente ragione.

Devi decodificare le entità tu stesso. Qualcosa di simile:

String decodeNumericEntities(String s) { 
    StringBuffer sb = new StringBuffer(); 
    Matcher m = Pattern.compile("\\&#(\\d+);").matcher(s); 
    while (m.find()) { 
     int uc = Integer.parseInt(m.group(1)); 
     m.appendReplacement(sb, ""); 
     sb.appendCodepoint(uc); 
    } 
    m.appendTail(sb); 
    return sb.toString(); 
} 

Tra l'altro quelle entità potrebbero derivare da moduli HTML processati, così sul lato di modifica della web app.


Dopo codice in questione:

ho sostituito con un DataInputStream (Buffered) Reader per il testo. InputStreams legge i dati binari, i byte; Testo dei lettori, archi. Un InputStreamReader ha come parametro un InputStream e una codifica e restituisce un Reader.

try { 
    BufferedReader input = new BufferedReader(
      new InputStreamReader(urlConn.getInputStream(), "UTF-8")); 
    StringBuilder strB = new StringBuilder(); 
    String str; 
    while (null != (str = input.readLine())) { 
     strB.append(str).append("\r\n"); 
    } 
    input.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

Sembra l'unica cosa che funzionerà. Grazie. – Ales

+0

Ho lo stesso problema, per favore aiuto. m.appendTail (m); questa linea mi errore. –

+0

@ ersyn61: Siamo spiacenti, corretto; avrebbe dovuto essere 'm.appendTail (sb);'. –

2

Beh, io sto pensando che il problema è quando si sta leggendo dal flusso. Dovresti chiamare il metodo readUTF invece di chiamare readLine oppure, cosa che farei, sarebbe creare un InputStreamReader e impostare la codifica, quindi puoi leggere dallo BufferedReader riga per riga (questo sarebbe all'interno del tuo tentativo esistente/catch):

Charset charset = Charset.forName("UTF8"); 
InputStreamReader stream = new InputStreamReader(urlConn.getInputStream(), charset); 
BufferedReader reader = new BufferedReader(stream); 
StringBuffer responseBuffer = new StringBuffer(); 

String read = ""; 
while ((read = reader.readLine()) != null) { 
    responseBuffer.append(read); 
} 
5

Prova ad aggiungere anche l'agente utente al URLConnection:

urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36"); 

Questo risolto il mio problema di decodifica come un fascino.

+1

cercavo questa risposta da giorni! – oferiko

Problemi correlati