从URL获取网站文本到字符串(Android)

时间:2014-02-03 23:00:09

标签: java android

首先,我必须说我是Android编程的初学者,并且在一般编程方面根本没有经验。但现在我决定为我的私人用途制作一个小应用程序。

在我的应用中,我需要将给定网址中的一些文本转换为字符串。我在网上找到了一些方法并对它们进行了个性化定制。但是有一些问题,因为当我使用Android Eclipse模拟器运行应用程序时,它说“不幸的是,xxx_app已停止。”。

这是我的代码:

    public String getURLtext(String zielurl) throws IllegalStateException, IOException{
    String meineurl = zielurl;

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(meineurl);
    HttpResponse response = httpClient.execute(httpGet, localContext);
    String result = "";

    BufferedReader reader = new BufferedReader(
        new InputStreamReader(
          response.getEntity().getContent()
        )
      );

    String line = null;
    while ((line = reader.readLine()) != null){
      result += line + "\n";
    }

    return result;          
}

这是我想在EditText text1中显示输出字符串的方法。

public void test(View view) throws InterruptedException, ExecutionException, IllegalStateException, IOException {

EditText text1 = (EditText)findViewById(R.id.textfeld);
String teststring = getURLtext("http://ephemeraltech.com/demo/android_tutorial20.php");
text1.setText(teststring);


}

如果有人能帮助我,我会很高兴。

谢谢!

1 个答案:

答案 0 :(得分:1)

在获得HTTPResponse之前,您的代码看起来很好,底部(对字符串的响应)可以进行很多优化。同样值得注意的是Android won't let you to do network operation on the main thread,因此请考虑使用AsyncTask来执行您的http GET操作。

public String getURLtext(String zielurl) throws IllegalStateException, IOException

{
    String result = ""; // default empty string
    try
    {
        String meineurl = zielurl;

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(meineurl);
    HttpResponse response = httpClient.execute(httpGet, localContext);

    InputStream is = response.getEntity().getContent();
    result = inputStreamToString(is).toString();
    }
    catch (Exception ex)
    {
       // do some Log.e here
    }
    finally
    {
        return result;          
    }
}

// Fast Implementation
private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();

    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    // Read response until the end
    try {
        while ((line = rd.readLine()) != null) { 
            total.append(line); 
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Return full string
    return total;
}