用Android发出HTTP请求

马茨·霍夫曼

我到处搜索过,但找不到答案,有没有办法发出简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但是我不想显示该页面。

如果可能的话,我什至想在后台(在BroadcastReceiver中)进行操作

康斯坦丁·布罗夫(Konstantin Burov)

更新

这是一个非常古老的答案。我绝对不会再推荐Apache的客户端。而是使用以下任一方法:

原始答案

首先,请求访问网络的权限,在清单中添加以下内容:

<uses-permission android:name="android.permission.INTERNET" />

然后,最简单的方法是使用与Android捆绑在一起的Apache http客户端:

    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);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

如果您希望它在单独的线程上运行,建议您扩展AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    @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);
                responseString = out.toString();
                out.close();
            } 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");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章