2013-02-12 64 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();