本帖最后由 ameyume 于 2010-08-21 14:38:02 编辑

解决方案 »

  1.   

    1.可以根据xml中解析出来的tag对应的设置相关中文
      

  2.   

    这样是可以,但挺麻烦,例如风速英语是mph,中文是米/秒,这样就涉及到转换了
      

  3.   

    之前我用这个链接,出来的是中文:
    http://www.google.cn/ig/api?weather=Beijing
      

  4.   

    现在得改成
    http://www.google.com.hk/ig/api?weather=Beijing
    O(∩_∩)O~
      

  5.   

    public class WeatherReport extends Activity implements OnClickListener {
    private static final String GOOGLE_API_URL = "http://www.google.com/ig/api?weather=";
    private static final String NETWORK_ERROR = "Network error!";
    private static final String TAG = "WEATHER_REPORT"; // Log tag
    private Spinner spinner; // city list
    private TextView tvWeatherInfo; // Display weather information

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            spinner = (Spinner) findViewById(R.id.spinner);        Button button = (Button) findViewById(R.id.goQuery);
            button.setOnClickListener(this);
            tvWeatherInfo = (TextView) findViewById(R.id.tvWeatherInfo);
        } @Override
    public void onClick(View v) {
      //获得用户输入的城市名称
          String city = spinner.getSelectedItem().toString();   // 必须每次都重新创建一个新的task实例进行查询,否则将提示如下异常信息
          // the task has already been executed (a task can be executed only once)
          new GetWeatherTask().execute(city);
          
          // Waiting message
          tvWeatherInfo.setText(R.string.querying);
    }
        
        // Get weather information
    public String getWeatherByCity(String city) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContent = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(GOOGLE_API_URL + city);

    try {
    HttpResponse response = httpClient.execute(httpGet, localContent);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    Log.e(TAG, "Failed. status code is not ok.");
    httpGet.abort();
    } else {
    // Get weather information successful
    HttpEntity httpEntity = response.getEntity();
    return parseWeather(httpEntity.getContent());
    }

    } catch (Exception e) {
    Log.e(TAG, "Failed to get weather information.", e);
    e.printStackTrace();
    } finally {
    // disconnect network
    httpClient.getConnectionManager().shutdown();
    }

    return NETWORK_ERROR;
    }
        
    // Parse InputStream to String
    public static String parseWeather(InputStream is) throws IOException { 
    List<CurrentCondition> list = DomXMLReader.readXML(is);
    CurrentCondition current = list.get(0);

    return "天气现象:" + new String(current.getCondition().getBytes(), "GB2312") + "\n"
     + "华氏温度:" + current.getTemp_f() + "\n"
     + "摄氏温度:" + current.getTemp_c() + "℃\n"
     + current.getHumidity() + "\n"
    //  + current.getIconPath() + "\n"
     + current.getWind_condition();
    }

    // Get weather task extends AsyncTask
    class GetWeatherTask extends AsyncTask<String, Integer, String> { @Override
    protected String doInBackground(String... params) {
    String city = params[0];
     
    // 调用Google天气API查询指定城市的当日天气情况
    return getWeatherByCity(city);
    }

    protected void onPostExecute(String result) {
    // 把doInBackground处理的结果即天气信息显示在TextView上
    tvWeatherInfo.setText(result);
    }
    }
    }DomXMLReader.java
    public class DomXMLReader {
    public static List<CurrentCondition> readXML(InputStream inStream) {
    List<CurrentCondition> currentList = new ArrayList<CurrentCondition>();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(inStream);
    Element root = dom.getDocumentElement();
    NodeList items = root.getElementsByTagName("current_conditions");//查找所有CurrentCondition节点
    for (int i = 0; i < items.getLength(); i++) {
    CurrentCondition currentCondition = new CurrentCondition();
    //得到第一个CurrentCondition节点
    Element currentNode = (Element) items.item(i);

    //获取person节点下的所有子节点(标签之间的空白节点和name/age元素)
    NodeList childsNodes = currentNode.getChildNodes();
    for (int j = 0; j < childsNodes.getLength(); j++) {
    Node node = (Node) childsNodes.item(j);
    //判断是否为元素类型
    if(node.getNodeType() == Node.ELEMENT_NODE){
    Element childNode = (Element) node;
                    //判断是否condition元素
        if ("condition".equals(childNode.getNodeName())) {
         //获取condition节点的data属性值
    currentCondition.setCondition(childNode.getAttribute("data"));
        } else if ("temp_f".equals(childNode.getNodeName())) {
         //获取temp_f节点的data属性值
         currentCondition.setTemp_f(childNode.getAttribute("data"));
        } else if ("temp_c".equals(childNode.getNodeName())) {
         //获取temp_c节点的data属性值
         currentCondition.setTemp_c(childNode.getAttribute("data"));
        } else if ("humidity".equals(childNode.getNodeName())) {
         //获取humidity节点的data属性值
         currentCondition.setHumidity(childNode.getAttribute("data"));
        } else if ("icon".equals(childNode.getNodeName())) {
         //获取iconPath节点的data属性值
         currentCondition.setIconPath(childNode.getAttribute("data"));
        } else if ("wind_condition".equals(childNode.getNodeName())) {
         //获取wind_condition节点的data属性值
         currentCondition.setWind_condition(childNode.getAttribute("data"));
        }
    }
        }
    currentList.add(currentCondition);
    }
    inStream.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return currentList;
    }
    }其中new String(current.getCondition().getBytes(), "GB2312")这样处理不起作用。
    用http://www.google.com.hk/ig/api?weather=Beijing得到的就是乱码
    各位看看该怎么改好?在哪个地方改呢?
      

  6.   

    用http://www.google.com.hk/ig/api?weather=Beijing查询,加big5转换也不行,还是乱码
      

  7.   

    new String(current.getCondition().getBytes(), "GB2312") 这句是没有用的,我发现所有的字串已经被转成了utf-8了,正在看是哪一步被转的。
      

  8.   

    多谢。使用这种形式http://www.google.com/ig/api?hl=zh-cn&weather=Beijing,查询出来的也还是乱码
      

  9.   

    终于知道错在哪里了,google返回的html格式不是标准格式,所以需要定义解析文字的格式。
    按照这个修改就OK了~~~                HttpEntity httpEntity = response.getEntity();
                    String string = EntityUtils.toString(httpEntity, "utf-8");
                    InputStream is = new ByteArrayInputStream(string.getBytes());
                    new DomXMLReader().readXML(is);
      

  10.   

    非常感谢版主!!!
    版主是怎么解决的?怎么查看返回到是什么格式的编码?
    还有google返回的html格式不标准是怎么看出来的?
      

  11.   

    1. 通过firefox查看的,返回的信息开头为<xml_api_reply version="1">,没有指明charset的格式,没有head信息。
    2. 标准的头格式为:
       <html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312">
      

  12.   

    多谢!
    原来如此!
    直接在ie中打开http://www.google.com/ig/api?weather=Beijing
    返回的xml文件里也是
     <?xml version="1.0" ?> 
    - <xml_api_reply version="1">
    没有charset属性,一致没有注意到呢!
      

  13.   

    firebug使开发web程序必不可少的工具啊呵呵版主经验很丰富
      

  14.   

    还是不行,
    解析出来的还是US标准的
    我增加了多语言的简体中文values-zh-rCN和美国英语values-en-rUS,只是多语言起作用

    HttpEntity httpEntity = response.getEntity();
    String string = EntityUtils.toString(httpEntity, "utf-8").trim();
    之前增加设置资源为简体中文的设置,即
    Resources resources = getResources();//获得res资源对象
    Configuration config = resources.getConfiguration();//获得设置对象
    DisplayMetrics dm = resources .getDisplayMetrics();//获得屏幕参数:主要是分辨率,像素等。
    config.locale = Locale.SIMPLIFIED_CHINESE; //简体中文
    resources.updateConfiguration(config, dm);

    // HttpResponse response = httpClient.execute(httpGet, localContent);
    HttpResponse response = httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    Log.e(TAG, "Failed. status code is not ok.");
    httpGet.abort();
    } else {
    // Get weather information successful
    // Reset charset
    HttpEntity httpEntity = response.getEntity();
    String string = EntityUtils.toString(httpEntity, "utf-8").trim();
    InputStream is = new ByteArrayInputStream(string.getBytes("utf-8"));
    return parseWeather(is);
    }
    取得string还是US标准的,取得的string如下所示
    <?xml version="1.0"?>
    <xml_api_reply version="1">
    <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
    <forecast_information>
    <city data="Beijing, Beijing"/>
    <postal_code data="&#x5317;&#x4EAC;"/>
    <latitude_e6 data=""/>
    <longitude_e6 data=""/>
    <forecast_date data="2010-08-23"/>
    <current_date_time data="2010-08-24 02:00:00 +0000"/>
    <unit_system data="US"/>
    </forecast_information>
    <current_conditions>
    <condition data="Cloudy"/>
    <temp_f data="79"/>
    <temp_c data="26"/>
    <humidity data="Humidity: 68%"/>
    <icon data="/ig/images/weather/cloudy.gif"/>
    <wind_condition data="Wind: S at 4mph"/>
    </current_conditions>
    <forecast_conditions>
    <day_of_week data="Mon"/>
    <low data="62"/>
    <high data="89"/>
    <icon data="/ig/images/weather/cloudy.gif"/>
    <condition data="Cloudy"/>
    </forecast_conditions>
    <forecast_conditions>
    <day_of_week data="Tue"/>
    <low data="60"/>
    <high data="84"/>
    <icon data="/ig/images/weather/cloudy.gif"/>
    <condition data="Cloudy"/>
    </forecast_conditions>
    <forecast_conditions>
    <day_of_week data="Wed"/>
    <low data="62"/>
    <high data="82"/>
    <icon data="/ig/images/weather/sunny.gif"/>
    <condition data="Clear"/>
    </forecast_conditions>
    <forecast_conditions>
    <day_of_week data="Thu"/>
    <low data="62"/>
    <high data="89"/>
    <icon data="/ig/images/weather/sunny.gif"/>
    <condition data="Clear"/>
    </forecast_conditions>
    </weather>
    </xml_api_reply>
      

  15.   

    把查询的API再改为这个就可以显示成简体中文了,
    http://www.google.com/ig/api?hl=zh-cn&weather=
    再加上版主说的
    HttpEntity httpEntity = response.getEntity();
    String string = EntityUtils.toString(httpEntity, "utf-8");
    InputStream is = new ByteArrayInputStream(string.getBytes());
    就OK了。
    多谢各位的相助!!