使用 android 发出 HTTP 请求

编程入门 行业动态 更新时间:2024-10-28 20:16:46
本文介绍了使用 android 发出 HTTP 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have searched everywhere but I couldn't find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I don't want to show the webpage.

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

If possible I even want to do it in the background (in a BroadcastReceiver)

推荐答案

UPDATE

这是一个非常古老的答案.我绝对不会再推荐 Apache 的客户端了.而是使用:

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

  • 改造
  • OkHttp
  • 排球
  • HttpUrlConnection

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

First of all, request a permission to access network, add following to your manifest:

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

那么最简单的方法就是使用Android自带的Apache http客户端:

Then the easiest way is to use Apache http client bundled with 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); String responseString = out.toString(); out.close(); //..more logic } else{ //Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); }

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

If you want it to run on separate thread I'd recommend extending 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.. } }

然后您可以通过以下方式提出请求:

You then can make a request by:

new RequestTask().execute("stackoverflow");

更多推荐

使用 android 发出 HTTP 请求

本文发布于:2023-11-26 22:51:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635530.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:android   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!