我想编写一个需要从服务器中恢复一些文本的应用程序 这是我的代码:
String db = ""
new Thread(new Runnable() {
@Override
public void run() {
try {
// Create a URL for the desired page
URL url = new URL("http://chemvaaj.xzn.ir/test/words.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
db+=str;
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
}).start();
searchEditText.setText(dbd);
似乎没错,但变量db最终是stil“。
答案 0 :(得分:1)
尝试以下代码:
希望能解决你的问题。
注意:首先,您必须在另一个线程中进行网络操作,因为主线程中的网络会使您的应用程序在任何请求的持续时间内无响应。所以将此代码放在AsyncTask。
中DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://chemvaaj.xzn.ir/test/words.txt");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder text = new StringBuilder();
String data;
while ((data= r.readLine()) != null) {
text .append(line + "\n");
}
searchEditText.setText(text );