我是Android新手。我正在开发一个简单的程序来访问web(weather.noaa.gov)并下载一个文本文件。以下是我的代码。我收到一条消息"网络已停止工作"。我在Manifest文件中添加了INTERNET权限。我感谢您的帮助。谢谢,山姆
public class MainActivity extends Activity {
private TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mTextView=(TextView) findViewById(R.id.textView1);
final Button loadButton =(Button) findViewById(R.id.load_button);
loadButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
new HttpGetTask().execute();
//enterClicked();
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String>{
//private static final String TAG ="HttpGetTask";
private static final String URL="http://weather.noaa.gov/pub/data/observations/metar/stations/KORD.TXT";
@Override
protected String doInBackground(Void...params){
String data=null;
HttpURLConnection httpUrlConnection = null;
try {
httpUrlConnection =(HttpURLConnection) new URL(URL).openConnection();
InputStream in =new BufferedInputStream(httpUrlConnection.getInputStream());
data = readStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
@Override
protected void onPostExecute(String result){
mTextView.setText(result);
}
private String readStream(InputStream in) {
//private void readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer data = new StringBuffer("");
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
//data += line +"\n";
data.append(line);
//System.out.println(line);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}