Android的http网络请求和发送
Android的http网络请求和发送
转载▼ 标签: androidhttp请求杂谈 |
原文地址:http://blog.sina.com.cn/s/blog_54ee89d90100np7p.html
这一章,会比较简单,由于目前的进度还没有到需要进行网络接口规划设计,所以没有花时间来架设服务端环境,进行联合调试。但是根据以往项目的经验,只要能够进行普通的HTTP请求,那么内部的网络请求也没有什么问题。所以这里,只是做一个测试。
从应用程序中发起一个HTTP连接,获得一个图片,并使用ImageView标签进行展现。
ImageView iv = new ImageView(context);
iv.setId(12351);
String imageUrl = "http://i.pbase.com/o6/92/229792/1/80199697.uAs58yHk.50pxCross_of_the_Knights_Templar_svg.png"; //标准HTTP地址即可
try {
URL myurl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
iv.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO: handle exception
}
layout.addView(iv);??? 可以看到发起一个网络请求是十分简单的。
同时,需要在Manifest.xml中加入uses-permission配置,允许进行网络访问。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.studio.crusoe.sample.android" android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ActivityMain" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="2" />
</manifest>
展现效果:
当然,如果进行正规的HTTP网络请求的调用,有更简单的API来使用,如HTTPClient:
1、使用Map来存储参数
Map<String, String> map = new HashMap<String, String>();
map.put(“name”, “wusheng”);
map.put(“password”, “pwd”);
2、使用DefaultHttpClient创建HttpClient实例
DefaultHttpClient httpClient = new DefaultHttpClient();
3、构建HttpPost
HttpPost post = new HttpPost(“http://wu-sheng.javaeye.com”);
4、将由Map存储的参数转化为键值参数
List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(),
entry.getValue()));
}
5、使用编码构建Post实体
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postData, HTTP.UTF_8);
6、设置Post实体
post.setEntity(entity);
7、执行Post方法
HttpResponse response = httpClient.execute(post);
8、获取返回实体
HttpEntity httpEntity = response.getEntity();
9、将H中返回实体转化为输入流
InputStream is = httpEntity.getContent();
10、读取输入流,即返回文本内容
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = “”;
while((line=br.readLine())!=null){
sb.append(line);
}
更多相关文章
- 网络对讲机C#服务器 Android客户端(三) android客户端代码分析 附
- android中做网络请求的几种方式
- Android 网络框架 Retrofit 源码解析
- Android 判断网络状态,并且在没有网络的时候,提示网络未开启
- lua学习笔记 3 android调用Lua。Lua脚本使用LoadLib回调Java,并
- Android 网络请求简单使用方式
- Android之网络请求2————OkHttp的基本使用
- Android DNS之DNS参数设置
- android(java)对网络状态(socket)判断的方法