1

我正在尝试启动第一个处理 Http 请求的应用程序。以下代码来自教程书,它不起作用:

package com.example.httpgetdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BufferedReader in = null;
        System.out.println("Before");
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://google.com/");
            HttpResponse response = client.execute(request);

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

            StringBuffer sb = new StringBuffer("");
            String line = "";

            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }

            in.close();
            String page = sb.toString();

            System.out.println(page);
        } catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

我说它不起作用是什么意思 - 我在手机上运行它,LogCat 显示第一个 System.out.println 但不显示第二个,错误提示:E/(1755): Can't open用于阅读的文件

我在这里阅读了一些关于以异步方式制作它的线程,但如果是这样,那么应用程序会崩溃,而且,更重要的是,这是一个书籍示例,所以它应该可以工作,不是吗?瞄准手机运行 ICS 怎么了?谢谢

4

0 回答 0