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

如果可能的话,我甚至想在后台做(在广播接收器中)

推荐答案

UPDATE

这是一个非常古老的答案.我肯定不会再推荐apache 的客户端了.请改为使用以下任一选项:

Original Answer

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

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

那么最简单的方法就是使用与AndroidBundle 的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");

Android相关问答推荐

将Android Studio插件复制到离线网络

如何在Jetpack composeH中创建具有弯曲末端的六边形形状

Android 14上的慢速意图广播交付

如何在Android Jetpack Compose中找到我的手机屏幕一行有多少个单词

在模块中找到重复的类com.google.Firebase.auth.ktx.AuthKt||Android Studio

为什么它显示我的空白屏幕?

在Android中使用Room从SQlite数据库中获取实体列表的正确方式是什么?

activity在 Runnable 中如何工作?我的 Android 表格未显示

在 kotlin 协同 routine 中,如何将数据范围限定为请求路径(以 MDC 为例)?

我怎样才能在多行 TextView 旁边有一个 ImageView 并且不超过父级的限制?

CoroutineScope 与挂起函数

AirDroid Business 如何能够从屏幕截图中排除覆盖?

在 Jetpack Compose 中重用具有重复代码的列

从 Firebase 云存储中获取照片会导致 Android Jetpack Compose 闪烁

删除一对多关系室 Kotlin 中的所有值

为什么我在 Jetpack Compose 中被警告可选修饰符参数应该具有默认值修饰符?

在开发过程中我应该把 mp4 文件放在哪里?

如何从我的 android 应用程序中删除 QUERY_ALL_PACKAGES 权限?

可扩展性 Qt 5.15 Android

可组合的 fillMaxSize 和旋转不起作用