您的位置:首页 > 理论基础 > 计算机网络

Android的http网络请求和发送

2014-10-29 16:06 225 查看


Android的http网络请求和发送


转载▼

标签:


android


http


请求


杂谈

原文地址: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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: