我是个新手,目前想在android app中发起一个简单的http请求,该请求到一个php页面左的网页上取一些数据,有没有可以通过后台运行去网站取数据并解析的功能?
第一步,把下面的代码加入到你的 manifest 文件中,目的是放开网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
然后就可以使用 Apache http client 访问页面了,在android中非常的简单就能完成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
HttpClient new
HttpResponse new
StatusLine if (statusLine.getStatusCode() ByteArrayOutputStream new
response.getEntity().writeTo(out); out.close(); String //..more } else { //Closes response.getEntity().getContent().close(); throw
} |
如果你想在后台访问或者异步的方式运行,需要继承 AsyncTask,AsyncTask是专门单独线程跑后台任务的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
class
extends
""
"" >{ @Override protected
HttpClient new
HttpResponse String null ; try
response new
0 ])); StatusLine if (statusLine.getStatusCode() ByteArrayOutputStream new
response.getEntity().writeTo(out); out.close(); responseString } else { //Closes response.getEntity().getContent().close(); throw
} } catch
//TODO } catch
//TODO } return
} @Override protected
super .onPostExecute(result); //Do } }</string,> |
最后你可以通过如下的方式调用
new RequestTask().execute("http://stackoverflow.com");