Android上的HTTP客户端

时间:2015-05-09 06:55:08

标签: java android eclipse apache http

我的HTTP客户端项目存在一些问题,使用HTTP方法GET,问题是,当我在Android模拟器上运行我的应用程序时它工作得很完美,当我在Java桌面应用程序中使用我的代码时,它也可以工作,但是当我在APK文件中导入并在我的Android设备上加载,我根本不起作用,我不知道为什么。

使用获取方法的类:

public class httpGetExClass {
    public String getInternetData() throws Exception {

        BufferedReader in = null;
        String data = null;
        try {
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://yumecms.com/absolvent/public/");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in .readLine()) != null) {
                sb.append(l + nl);
            } in .close();
            data = sb.toString();
            return data;
        } finally {
            if ( in != null) {
                try { in .close();
                    return data;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

这是MainActivity

public class MainActivity extends Activity implements OnClickListener {

    TextView tv1;@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.textView1);
    }

    @Override
    public void onClick(View arg0) {
        httpGetExClass httpGet = new httpGetExClass();
        httpPostExClass httPost = new httpPostExClass();
        switch (arg0.getId()) {
            case R.id.buttonEnter:

                try {
                    Toast.makeText(this, "!!!!", Toast.LENGTH_SHORT).show();
                    String returned = httpGet.getInternetData();
                    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
                    tv1.setText(returned);
                } catch (Exception e) {
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }


                break;
        }

    }
}

1 个答案:

答案 0 :(得分:1)

您的代码是阻止的,Android中不允许这样做。您必须为您的httpclient使用另一个线程或使用特定于Android的AsyncTask