2013-02-12 63 views
0

我是新來的Java,我試圖創建一個從Web服務獲取巴西地址的庫,但我無法讀取響應。從Java的網頁閱讀文本

在類的構造函數中我有這個result字符串,我想追加回應,一旦這個變量填充了響應,我會知道該怎麼做。

的問題是:由於某種原因,我猜BufferedReader對象不工作所以要讀無反應:/

下面是代碼:

package cepfacil; 

import java.net.*; 
import java.io.*; 
import java.io.IOException; 

public class CepFacil { 
    final String baseUrl = "http://www.cepfacil.com.br/service/?filiacao=%s&cep=%s&formato=%s"; 
    private String zipCode, apiKey, state, addressType, city, neighborhood, street, status = ""; 

    public CepFacil(String zipCode, String apiKey) throws IOException { 
     String line = ""; 

     try { 
      URL apiUrl = new URL("http://www.cepfacil.com.br/service/?filiacao=" + apiKey + "&cep=" + 
        CepFacil.parseZipCode(zipCode) + "&formato=texto"); 

      String result = ""; 

      BufferedReader in = new BufferedReader(new InputStreamReader(apiUrl.openStream())); 

      while ((line = in.readLine()) != null) { 
       result += line; 
      } 
      in.close(); 

      System.out.println(line); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 

     this.zipCode = zipCode; 
     this.apiKey = apiKey; 
     this.state = state; 
     this.addressType = addressType; 
     this.city = city; 
     this.neighborhood = neighborhood; 
     this.street = street; 
    } 
} 

因此,這裏是如何代碼應該工作,你建立這樣一個對象:

String zipCode = "53416-540"; 
String token = "0E2ACA03-FC7F-4E87-9046-A8C46637BA9D"; 

CepFacil address = new CepFacil(zipCode, token); 

// so the apiUrl object string inside my class definition will look like this: 
// http://www.cepfacil.com.br/service/?filiacao=0E2ACA03-FC7F-4E87-9046-A8C46637BA9D&cep=53416540&formato=texto 
// which you can check, is a valid url with content in there 

我省略稱爲構造函數的代碼爲簡潔的某些部分,但所有的方法在我的代碼中定義,沒有編譯或運行時錯誤。

我會很感激任何幫助,您可以給我,我很樂意聽到的最簡單的解決方案,更多鈔票:)

提前感謝!

更新:現在,我可以解決這個問題(巨大的道具@Uldz指着我的問題出來了),它是開源,開源http://www.rodrigoalvesvieira.com/cepfacil/

回答

1

System.out.println(line + "rodrigo"); 

你輸出線沒有結果。也許最後一行是空的?

+0

awwww男人,就是這樣。謝謝!巨大的謝意! – rodrigoalves 2013-02-12 12:53:59

0

可能有多種原因。 將您的URL包裝在HttpURLConnection中,這將幫助您查看響應代碼和有關您從服務器獲得的響應的更多信息。

0

您可以/應該爲InputStreamReader添加編碼。 然後結果不會添加換行符。

 BufferedReader in = new BufferedReader(new InputStreamReader(apiUrl.openStream())); 

     while ((line = in.readLine()) != null) { 
      System.out.println("Line: " + line); 
      String[] keyValue = line.split("\\s*=\\s*", 2); 
      if (keyValue.length != 2) { 
       System.err.println("*** Line: " + line); 
       continue; 
      } 
      switch (keyValue[0]) { 
       case "status": 
        status = keyValue[1]; 
        break; 
       ... 
       default: 
        System.err.println("*** Key wrong: " + line); 
      } 
      result += line + "\n"; 
     } 
     in.close();