无法读取从服务器文本(Not Reading text from server)

2019-07-29 18:40发布

我想读所有从服务器的文本,我认为我的代码不会检索从服务器的文字,你会请帮我,我怎么能解决这个问题,我是新来的Android开发。 提前致谢

public class TestActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv= (TextView)findViewById(R.id.my_text);


                try {

                    URL url = new URL("http://www.google.com:80/");
                    StringBuilder content = new StringBuilder();
                    // read text returned by server

                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        content.append(line +"\n");
                    }
                    tv.setText(content.toString());
                    setContentView(tv);

                    in.close();
                }

                catch (MalformedURLException e) {

                    System.out.println("Malformed URL: " + e.getMessage());

                }

                catch (IOException e) {

                    System.out.println("I/O Error: " + e.getMessage());

                }


};        


}

Answer 1:

把这些线

tv.setText(line);
setContentView(tv);

出while循环

在while循环使用StringBuilder对象(循环前声明),并附加了字符串。 从StringBuilder的while循环取字符串后,做tv.setText(串)



Answer 2:

可能是你可以尝试这样的,只是一个想法只有:

StringBuilder content = new StringBuilder();
                // read text returned by server
                BufferedReader in = new BufferedReader(new InputStreamReader(new URL("http://www.google.com:80/").openConnection().getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    content.append(line +"\n");
                }

tv.setText(content.toString());
setContentView(tv);


文章来源: Not Reading text from server