无法从网站android上的文件中获取文本

时间:2014-11-25 20:05:01

标签: android android-internet

我正在尝试从一个简单的文本文件中提取文本,该文本文件是直接访问我可以使用我的代码中使用的链接访问的网站,但由于某些原因它无法正常工作。使用调试工具我发现它在HttpResponse行之后抛出一个异常。我不知道如何解决这个问题。(对不起我的长问题,我是android和stackoverflow的新手)

package com.example.trial;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    TextView TextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            HttpGet httppost = new HttpGet(
                    "http://www.androidworkshopmit.webs.com/abc.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");
            }
            TextView.setText(total);
        } catch (Exception e) {
            System.out.print("hi, there is some error!");
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

  

我的代码但由于某种原因它不起作用。使用调试工具我发现它在HttpResponse行之后抛出异常。

您正在主UI线程上执行网络操作(HTTP GET调用)。使用AsyncTask在后台线程中进行所有网络调用。以下是如何使用它的基本示例:How to use AsyncTask correctly in Android