android 发送一个http请求的问题
来源:互联网 发布:python创建字典 编辑:程序博客网 时间:2024/05/22 16:56
我是个新手,目前想在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 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是专门单独线程跑后台任务的类
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
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);
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..
}
}</string,>
最后你可以通过如下的方式调用
new RequestTask().execute("http://stackoverflow.com");
原文地址:http://www.itmmd.com/201410/91.html
0 0
- android 发送一个http请求的问题
- Android 发送HTTP请求出现编码问题
- android发送http请求
- android 发送http请求
- Xcode7发送HTTP请求的问题
- Xcode7发送http请求失败的问题
- Android的http网络请求和发送
- android发送HTTP请求模板
- android http 发送json请求
- Android 发送http请求实例
- Android如何发送HTTP请求
- Android网络:发送http请求
- 一个http请求发送到后端的详细过程
- 一个http请求发送到后端的详细过程
- 一个http请求发送到后端的详细过程
- 一个HTTP请求引发的问题
- 关于HTTP客户端重复发送请求的问题
- Xcode7 使用NSURLSession发送HTTP请求的问题
- python中对文件、文件夹的操作 os模块
- android bindService() NullPointerException
- C++操作符优先级
- Android BInder
- 三种方式求杨辉三角形
- android 发送一个http请求的问题
- 游戏被App Store下架 如何快速上线?
- 写在前面的话
- hdu 2485 迭代加深搜索
- 计算机经典书籍电子书合集(适合计算机学生学习以及程序员笔试、面试)
- matlab 二值化;MFC 显示灰度图片方法。
- NYOJ305表达式求值
- Java断点调试
- 第17周项目5--玩日期时间(两个日期天数之差,秒数之差)