android 发送一个http请求的问题

文章标签:
2014-10-31 13:24:07     人阅读    

我是个新手,目前想在android app中发起一个简单的http请求,该请求到一个php页面左的网页上取一些数据,有没有可以通过后台运行去网站取数据并解析的功能?

第一步,把下面的代码加入到你的 manifest 文件中,目的是放开网络访问权限
<uses-permission android:name="android.permission.INTERNET" />

然后就可以使用 Apache http client 访问页面了,在android中非常的简单就能完成

HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

如果你想在后台访问或者异步的方式运行,需要继承 AsyncTask,AsyncTask是专门单独线程跑后台任务的类

class RequestTask extends AsyncTask{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

最后你可以通过如下的方式调用

new RequestTask().execute("http://stackoverflow.com");


原文地址:http://www.itmmd.com/201410/91.html
该文章由 萌萌的IT人 整理发布,转载须标明出处。

android bindService() NullPointerException   上一篇
下一篇  在android 中发送和解析json ,android处理json字符串
精彩回复
我要追加问题,请求站长解决!
姓名:       

《程序员app》专门为程序员量身定做!