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);
// 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()); }
http://www.google.cn/ig/api?weather=Beijing
http://www.google.com.hk/ig/api?weather=Beijing
O(∩_∩)O~
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得到的就是乱码
各位看看该怎么改好?在哪个地方改呢?
按照这个修改就OK了~~~ HttpEntity httpEntity = response.getEntity();
String string = EntityUtils.toString(httpEntity, "utf-8");
InputStream is = new ByteArrayInputStream(string.getBytes());
new DomXMLReader().readXML(is);
版主是怎么解决的?怎么查看返回到是什么格式的编码?
还有google返回的html格式不标准是怎么看出来的?
2. 标准的头格式为:
<html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312">
原来如此!
直接在ie中打开http://www.google.com/ig/api?weather=Beijing
返回的xml文件里也是
<?xml version="1.0" ?>
- <xml_api_reply version="1">
没有charset属性,一致没有注意到呢!
解析出来的还是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="北京"/>
<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>
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了。
多谢各位的相助!!