`

android HttpURLConnection编程详解,获取网络图片,html代码查

 
阅读更多

本文出自:http://blog.csdn.net/zhongnan09/article/details/6565130

在Android中,使用http协议的编程工作是比较简单的,androidSDK中已经集成了Apache的HttpClient模块。使用HttpClient可以快速开发出功能强大的Http程序。不过一般说来,要开发与Internet连接的程序,最基础的还是使用HttpURLConnection。

下面是一个使用HttpURLConnection对象从互联网上读取数据的Demo:

第一个Demo是从互联网上读取某个图片:

首先在Eclipse中新建一个工程ImageView。而后新建一个Activity名称为MainActivity:

package com.xzq.image;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.Toast;

public class MainActivity extends Activity {

private static final String TAG = "MainActivity";

private EditText pathText;

private ImageView imageView;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

pathText = (EditText) this.findViewById(R.id.urlpath);

imageView = (ImageView) this.findViewById(R.id.imageView);

Button button = (Button) this.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String path = pathText.getText().toString();

try {

byte[] data = getImage(path);

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,

data.length);

imageView.setImageBitmap(bitmap);

} catch (Exception e) {

Toast.makeText(MainActivity.this, R.string.error, 1).show();

Log.e(TAG, e.toString());

}

}

});

}

public static byte[] getImage(String path) throws Exception {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5 * 1000);

InputStream inStream = conn.getInputStream();

return readFromInput(inStream);

}

public static byte[] readFromInput(InputStream inStream) throws Exception {

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while ((len = inStream.read(buffer)) != -1) {

outStream.write(buffer, 0, len);

}

inStream.close();

return outStream.toByteArray();

}

}

布局文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent">

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="@string/urlpath" />

<EditText android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="http://www.baidu.com/img/baidu_sylogo1.gif"

android:id="@+id/urlpath" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="@string/button"

android:id="@+id/button" />

<ImageView android:layout_width="wrap_content"

android:layout_height="wrap_content" android:id="@+id/imageView" />

</LinearLayout>

最后一项要注意的地方是,要运行该工程,必须在AndroidManifest.xml文件中加上访问网络的权限:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.xzq.image" android:versionCode="1" android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".MainActivity"

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="8" />

<!-- 访问网络的权限 -->

<uses-permission android:name="android.permission.INTERNET" />

</manifest>

结果:

第二个例子是一个Html代码查看器,主要为演示如何从互联网上获取网页数据:

同样,在Eclipse中新建一个工程,创建启动Activity,命名为MainActivity:

package com.xzq.htmlcode;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

TextView textView = (TextView) this.findViewById(R.id.textView);

try {

textView.setText(getHtmlCode("http://www.sohu.com"));

} catch (Exception e) {

Log.e("MainActivity", e.toString());

Toast.makeText(MainActivity.this, "网络连接失败", 1).show();

}

}

public static String getHtmlCode(String path) throws Exception {

URL url = new URL(path);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(5 * 1000);

InputStream inStream = conn.getInputStream();

byte[] data = readFromInput(inStream);

String html = new String(data, "gbk");

return html;

}

public static byte[] readFromInput(InputStream inStream) throws Exception {

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while ((len = inStream.read(buffer)) != -1) {

outStream.write(buffer, 0, len);

}

inStream.close();

return outStream.toByteArray();

}

}

布局文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<ScrollView

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/textView"

/>

</ScrollView>

</LinearLayout>

结果如图:

要注意加上ScrollView标签,否则,当页面数据比较大时,不能出现滚动条,影响使用。另外,同样要在AndroidManifest.xml文件中添加访问网络的权限,见上例。

这两个例子本身并没有实际的应用价值,只是展示了如何使用HttpURLConnection对象实现联网,并从互联网上读取图片、网页文件等数据。使用HttpURLConnection对象进行网络编程的核心过程也就是如此了。当然,HttpURLConnection对象还有很多方法,可以设置访问访问请求头字段等信息。感兴趣的朋友可以发送邮件到我的邮箱,共同探讨。

在后面的一篇文章中,我将会跟大家讨论使用post方式上传数据,包括文件等。


分享到:
评论

相关推荐

    Android开发使用HttpURLConnection进行网络编程详解【附源码下载】

    本文实例讲述了Android开发使用HttpURLConnection进行网络编程。分享给大家供大家参考,具体如下: ——HttpURLConnection URLConnection已经可以非常方便地与指定站点交换信息,URLConnection下还有一个子类:...

    《Android应用开发揭秘》附带光盘代码.

     6.5.2 SQLite编程详解  6.5.3 SQLiteOpenHelper应用  6.6 数据共享(ContentProviders)  6.7 小结  第7 章多媒体开发  7.1 多媒体开发详解  7.1.1 Open Core  7.1.2 MediaPlayer  7.1.3 MediaRecorder  ...

    android开发揭秘PDF

    6.5.2 SQLite编程详解 6.5.3 SQLiteOpenHelper应用 6.6 数据共享(ContentProviders) 6.7 小结 第7 章多媒体开发 7.1 多媒体开发详解 7.1.1 Open Core 7.1.2 MediaPlayer 7.1.3 MediaRecorder 7.2 播放音乐 7.3 播放...

    Android实例代码

    13.5、使用WebService进行网络编程: 第14章、管理Android手机桌面 14.1、管理手机桌面: 14.2、改变手机壁纸: 14.3、桌面快捷方式: 14.4、管理桌面小控件: 14.5、实时文件夹(LiveFolder): 第15章、传感器...

    《Android应用开发揭秘》源码

     6.5.2 SQLite编程详解  6.5.3 SQLiteOpenHelper应用  6.6 数据共享(ContentProviders)  6.7 小结  第7 章多媒体开发  7.1 多媒体开发详解  7.1.1 Open Core  7.1.2 MediaPlayer  7.1.3 MediaRecorder  ...

    Android应用开发揭秘pdf高清版

    6.5.2 SQLite编程详解 6.5.3 SQLiteOpenHelper应用 6.6 数据共享(ContentProviders) 6.7 小结 第7 章多媒体开发 7.1 多媒体开发详解 7.1.1 Open Core 7.1.2 MediaPlayer 7.1.3 MediaRecorder 7.2 播放音乐 7.3 播放...

    疯狂Android讲义源码

     第2章 Android应用的界面编程 35  2.1 界面编程与视图(View)组件 36  2.1.1 视图组件与容器组件 36  2.1.2 使用XML布局文件控制UI  界面 40  2.1.3 在代码中控制UI界面 41  2.1.4 使用XML布局文件和Java ...

    疯狂Android讲义(第2版)源代码 第6章~第9章

    13.5、使用WebService进行网络编程: 第14章、管理Android手机桌面 14.1、管理手机桌面: 14.2、改变手机壁纸: 14.3、桌面快捷方式: 14.4、管理桌面小控件: 14.5、实时文件夹(LiveFolder): 第15章、传感器...

    疯狂Android讲义.part2

    第1章 Android应用与开发环境 1 1.1 Android的发展和历史 2 1.1.1 Android的发展和简介 2 1.1.2 Android平台架构及特性 3 1.2 搭建Android开发环境 5 1.2.1 下载和安装Android SDK 5 1.2.2 安装Eclipse和ADT插件 7 ...

    疯狂Android讲义.part1

    第1章 Android应用与开发环境 1 1.1 Android的发展和历史 2 1.1.1 Android的发展和简介 2 1.1.2 Android平台架构及特性 3 1.2 搭建Android开发环境 5 1.2.1 下载和安装Android SDK 5 1.2.2 安装Eclipse和ADT插件 7 ...

    Android编程开发实现带进度条和百分比的多线程下载

    本文实例讲述了Android编程开发实现带进度条和百分比的多线程下载。分享给大家供大家参考,具体如下: 继上一篇《java多线程下载实例详解》之后,可以将它移植到我们的安卓中来,下面是具体实现源码: DownActivity....

Global site tag (gtag.js) - Google Analytics