2012-02-21 43 views
0

我使用此代碼從網頁中讀取數據:從java中的網頁讀取數據時出錯?

public class ReadLatex { 
public static void main(String[] args) throws IOException { 
    String urltext = "http://chart.apis.google.com/chart?cht=tx&chl=1+2%20\frac{3}{4}"; 
    URL url = new URL(urltext); 
    BufferedReader in = new BufferedReader(new InputStreamReader(url 
      .openStream())); 
    String inputLine; 

    while ((inputLine = in.readLine()) != null) { 
     // Process each line. 
     System.out.println(inputLine); 
    } 
    in.close(); 
    } 
} 

的網頁給出了URL中的乳膠碼的圖像。

我得到這個異常:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: http://chart.apis.google.com/chart? 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) 
at java.net.URL.openStream(Unknown Source) 
at ReadLatex.main(ReadLatex.java:11) 

誰能告訴我爲什麼有這個問題,應該是什麼這樣的解決方案?

+1

400指錯誤的請求 - 這意味着請求無法被服務器因爲語法錯誤理解....你嘗試一些其他的網址? – 2012-02-21 09:35:40

+1

你應該逃避你所有的特殊字符,並在URL – 2012-02-21 09:36:37

回答

1

你的問題是你在一個字符串中使用了一個\(反斜槓),在Java中是一個轉義字符。爲了得到一個實際的\你需要在你的字符串中有兩個。所以:

Wanted text: part1\part2 

你需要有

String theString = "part1\\part2"; 

所以你真正想要

String urltext = "http://chart.apis.google.com/chart?cht=tx&chl=1+2%20\\frac{3}{4}"; 

此外,當您與您的要求成功,你回來的圖像(PNG),它不應該用閱讀器閱讀,閱讀器會嘗試將字節解釋爲使用某種編碼的字符,這會破壞圖像數據。相反,使用輸入流並將內容(字節)寫入文件。

一個簡單的例子,而不錯誤處理

public static void main(String[] args) throws IOException { 
    String urltext = "http://chart.apis.google.com/chart?cht=tx&chl=1+2%20\\frac{3}{4}"; 
    URL url = new URL(urltext); 

    InputStream in = url.openStream(); 
    FileOutputStream out = new FileOutputStream("TheImage.png"); 

    byte[] buffer = new byte[8*1024]; 
    int readSize; 
    while ((readSize = in.read(buffer)) != -1) { 
     out.write(buffer, 0, readSize); 
    } 
    out.close(); 
    in.close(); 
} 
+0

斜線先生,我已經嘗試過新的代碼,但在控制檯它顯示不可讀的字符。我讀你的答案,但無法弄清楚如何做到這一點。 – Navdroid 2012-02-21 13:18:52

+0

你能幫我一些代碼或教程嗎 – Navdroid 2012-02-21 13:19:15

+0

@Navdroid你在問什麼而不是你的問題的答案。您的http問題已解決。您錯過的是使用HTTP響應內容的方式。這是一個明顯的問題。更新或拆分你的問題不是更好嗎? – 2012-02-21 16:26:43

1

我認爲你應該考慮轉義URL中的反斜槓。我的Java,反斜槓必須在字符串 轉義應該成爲

String urltext = 
      "http://chart.apis.google.com/chart?cht=tx&chl=1+2%20\\frac{3}{4}"; 

這是爲純java開始。 看來,這個網址適用於我的瀏覽器,但正如在其他答案建議,我認爲它應該更好地逃脫所有的特殊字符,如反斜槓,鞋帶... ...

2

嘗試逃避像org .apache.commons.lang.StringEscapeUtils