我用它连接到互联网并检索页面源,非常简单:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_library);
String data = "";
if(!isNetworkAvailable()){
TextView tv = (TextView) findViewById(R.id.placeholder);
tv.setText("No Connection!!!");
return;
}
try{
URL url = null;
url = new URL("http://google.com");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
data += line;
}
TextView tv = (TextView) findViewById(R.id.placeholder);
tv.setText(data);
}catch(Exception e){
TextView tv = (TextView) findViewById(R.id.placeholder);
tv.setText("error : "+e.toString());
}
}
但数据不会从互联网上回来。 有什么问题?
答案 0 :(得分:0)
您需要在后台任务中放置从互联网检索数据的代码,以便在服务或AsyncTask中。
答案 1 :(得分:0)
尝试以下代码: -
TextView tv = (TextView) findViewById(R.id.placeholder);
if(!isNetworkAvailable()){
tv.setText("No Connection!!!");
new ChangePasswordAsyncTask().execute();
return;
}
private class ConnectToServer extends AsyncTask<String, String, String>
{
private String data;
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(String... params)
{
try
{
// do stuff from server
URL url = null;
url = new URL("http://google.com");
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
data += line;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}
@Override
protected void onProgressUpdate(String... values)
{
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
// String jData = "";
try
{
// set UI on this method
tv.setText(data);
}
catch (Exception e)
{
e.printStackTrace();
// Toast.makeText(context, jMessage, Toast.LENGTH_LONG).show();
}
}
}
答案 2 :(得分:0)
您是否有权使用清单访问INTERNET?