我正在尝试从googles API解析天气信息,当WIFI连接时它可以正常工作,但是当手机通过3G连接到互联网时却没有。
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Toast;
public class GetWeather2 extends Activity{
static final String baseURL = "http://www.google.com/ig/api?weather=";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.getweather2);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
String c = "mycity";
StringBuilder URL = new StringBuilder(baseURL);
URL.append(c);
String fullURL = URL.toString();
try{
URL website = new URL(fullURL);
//getting xmlreader to parse data
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String[] weatherInfo = new String[] {};
weatherInfo = doingWork.getInformation();
information[5] = weatherInfo[0];
information[3] = weatherInfo[1];
//tv.setText(information);
Intent i = new Intent("blabla");
i.putExtra("information", information);
startActivity(i);
finish();
}catch (Exception e){
Toast.makeText(this, "error weather", Toast.LENGTH_SHORT).show();
Intent i = new Intent("com.blaabla");
i.putExtra("information", information);
startActivity(i);
finish();
}
}
}
(为了便于阅读,我缩小了代码)
我已经检查了手机网络浏览器中的完整网址,并且XML文档在使用wifi时看起来很好但是当它关闭时,页面显示它不可用。