简体   繁体   English

从互联网检索数据

[英]Retrieving data from the internet

The following code is from my first internet app. 以下代码来自我的第一个互联网应用。 I have not tested it because there is no WLAN available for me. 我没有测试它,因为没有可用的WLAN。 What I want to do next is to retrieve data from the website. 我接下来要做的是从网站上检索数据。

Is there any procedure to follow to achieve such task? 有什么程序可以完成这项任务?

JAVA Code: JAVA代码:

public class Internet00 extends Activity {

TextView tv00;
public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netWorkinfo = cm.getActiveNetworkInfo();

    if (netWorkinfo != null && netWorkinfo.isConnected()) {
        return true;
    }
    return false;
}
private void readStream(InputStream in) {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader (in));
        String line="";
        while ( (line=reader.readLine()) != null)
            tv00.setText(line);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException e) {
            e.printStackTrace();
            }
        }
    }
}
@SuppressLint({ "ParserError", "NewApi" })
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_internet00);

    tv00 = (TextView) findViewById(R.id.tv00);
    if(isNetworkAvailable()) {
        StrictMode.ThreadPolicy policy = new StrictMode.
            ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

    try {
          URL url = new URL("http://www.vogella.com");
          HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
          readStream(con.getInputStream());
        } catch (Exception e) {
          e.printStackTrace();
           }
        }
    }
}

Could you be a little more specific? 您能具体一点吗?

It looks to me like you're retrieving the data already. 在我看来,您已经在检索数据。

Your code should fail, because of you're doing network stuff in the UI Thread. 您的代码应该失败,因为您正在UI线程中做网络工作。

Yes of-course, you need to follow some rules. 当然可以,您需要遵循一些规则。

  1. Please don't use network thread in UI thread 请不要在UI线程中使用网络线程
  2. Use AsyncTask for download related works 使用AsyncTask下载相关作品

A working example can be found here : Getting info from api using JSON 可以在这里找到一个工作示例: 使用JSON从api获取信息

Refer my answer in above post to download data from a server to your device. 请参阅以上文章中的我的答案,以将数据从服务器下载到您的设备。 This working example can be a good start for you. 这个工作示例可以为您提供一个良好的开端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM