Android HTTP请求访问

     这一章,会比较简单,由于目前的进度还没有到需要进行网络接口规划设计,所以没有花时间来架设服务端环境,进行联合调试。但是根据以往项目的经验,只要能够进行普通的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.iteye.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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值