參考Mars的方式為了要下載檔案,獨立寫了一個類別HttpDownloader.java 方便以後的引用
避免不必要的重複代碼
HttpDownloader.java
------------------------------------------------
public class HttpDownloader {
private URL myurl=null;
public String download(String urlstr){
StringBuffer sb=new StringBuffer();
String line=null;
BufferedReader buffer= null;
try {
myurl = new URL(urlstr);
HttpsURLConnection con= (HttpsURLConnection) myurl.openConnection();
con.connect();
buffer=new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line=buffer.readLine())!=null) {
//sb.append(line);
sb.append(line);
//System.out.println("testest");
//System.out.println(sb.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sb.toString();
}
}
-----------------------------------
然後要使用時,在MainActivity.java使用
MainActivity.java
-----------------------------------
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button btGetxml=(Button)findViewById(R.id.button1);
btGetxml.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView tv1=(TextView)findViewById(R.id.tv1);
HttpDownloader httpDownloader=new HttpDownloader();
String getxml=httpDownloader.download("https://weather.yahooapis.com/forecastrss?w=2306179");
System.out.println(getxml);
//tv1.setText(getxml);
try {
//使用DOM解析XML
DocumentBuilderFactory dfactory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dfactory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(getxml)));
//
沒有留言:
張貼留言