Android从服务器读取文本文件

时间:2015-08-22 19:10:46

标签: android

我知道这个问题已经被要求死亡,但我没有获胜,我正在尝试将服务器中的文本文件读成字符串,它刚刚工作了一段时间,但最后一段仅显示符号。然后我将我的charset指定为“UTF-8”,希望它能解决我的问题,但现在整个文本文件显示符号。这是我的代码:

URL url = new URL("http://lehakoeevents.co.za/dijo/weekly_content/stories/sway_rustenburg_22_08_15.txt");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

InputStream in = connection.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.

String story = bo.toString();
Log.i("", "New Response : " + story);

我尝试将以下内容添加到我的连接请求中:

connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

但仍然在各处展示符号,请帮忙。

1 个答案:

答案 0 :(得分:1)

试试这个

            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httppost = new HttpGet(
                    "http://lehakoeevents.co.za/dijo/weekly_content/stories/sway_rustenburg_22_08_15.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 total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line + "\n");
            }
            Log.i("HI", "" + total.toString());

希望这有帮助!