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

本文实例讲述了Android开发使用HttpURLConnection进行网络编程。分享给大家供大家参考,具体如下:

——HttpURLConnection

URLConnection已经可以非常方便地与指定站点交换信息,URLConnection下还有一个子类:HttpURLConnection,HttpURLConnection在URLConnection的基础上进行改进,增加了一些用于操作HTTP资源的便捷方法。

setRequestMethod(String):设置发送请求的方法

getResponseCode():获取服务器的响应代码

getResponseMessage():获取服务器的响应消息

a)get请求的代码:

conn=(HttpURLConnection)url.openConnection();

conn.setRequestMethod("GET");

conn.setConnectTimeout(8000);//连接超时的毫秒数

conn.setReadTimeout(8000);//读取超时的毫秒数

b)post请求的代码

conn=(HttpURLConnection)url.openConnection();

conn.setRequestMethod("POST");

c)关闭连接

if(conn!=null)conn.disconnect();

实现多线程下载的步骤:

a)创建URL对象

b)获取指定URL对象所指向资源的大小:getContentLength()

c)在本地磁盘上创建一个与网络资源相同大小的空文件

d)计算每条线程应用下载网络资源的指定部分

e)依次创建,启动多条线程来下载网络资源的指定部分

注意需要的权限:

这里我简单的使用一下HttpURLConnection来进行文本解析和图片解析

编程步骤如下:

1.先写布局文件:

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="click"

android:text="加载图片"

/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

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

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="click2"

android:text="加载文本"

/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

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

2.在MainActivity中文本解析的实现:

//文本解析

public void click2(View view){

new Thread(){

public void run() {

try {

URL url2=new URL("http://www.baidu.com");

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

conn.setRequestMethod("GET");

conn.setConnectTimeout(8000);

conn.setReadTimeout(8000);

conn.connect();

if(conn.getResponseCode()==200){

InputStream inputStream=conn.getInputStream();

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

byte[]b=new byte[512];

int len;

while ((len=inputStream.read(b))!=-1) {

byteArrayOutputStream.write(b,0,len);

}

String text=new String(byteArrayOutputStream.toByteArray(),"UTF-8");

Message msg=Message.obtain();

msg.what=0x124;

msg.obj=text;

handler.sendMessage(msg);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

};

}.start();

}

这里使用了GET方式~也可以用POST方式~

3.在MainActivity中图片解析的实现:

//图片解析

public void click(View view){

final File file=new File(getCacheDir(),"2.png");

if(file.exists()){

System.out.println("使用缓存");

Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());

iv.setImageBitmap(bitmap);

}else{

new Thread(){

public void run() {

try {

URL url=new URL("http://192.168.207.1:8090/2.png");

System.out.println("使用网络");

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

conn.setRequestMethod("GET");

conn.setConnectTimeout(8000);

conn.setReadTimeout(8000);

conn.connect();

if(200==conn.getResponseCode()){

//正常连接

InputStream is=conn.getInputStream();

//Bitmap bitmap=BitmapFactory.decodeStream(is);

FileOutputStream fileOutputStream=new FileOutputStream(file);

int len;

byte[] b=new byte[1024];

while ((len=is.read(b))!=-1) {

fileOutputStream.write(b,0,len);

}

fileOutputStream.close();

Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());

fileOutputStream.flush();

Message msg=Message.obtain();

msg.what=0x123;

msg.obj=bitmap;

handler.sendMessage(msg);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

};

}.start();

}

}

这个图片解析实现了图片的缓存,想要再一次加载图片的时候,就可以到缓存的文件中得到图片,就可以减少内存的使用~

这个图片我是放在服务器端的这个目录下\apache-tomcat-7.0.37\webapps\upload,从服务器上可以下载这个图片,然后保存在文件中~

4.最后,把文本和图片加载出来

private Handler handler=new Handler(){

public void handleMessage(android.os.Message msg) {

if(msg.what==0x123){

Bitmap bitmap=(Bitmap) msg.obj;

iv.setImageBitmap(bitmap);

}

else if(msg.what==0x124){

String text=(String) msg.obj;

tv.setText(text);

}

};

};

效果图我就不贴了,知道代码怎么写就行~

完整MainActivity代码如下:

public class MainActivity extends Activity {

private ImageView iv;

private TextView tv;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

iv=(ImageView) findViewById(R.id.iv);

tv=(TextView) findViewById(R.id.tv);

}

private Handler handler=new Handler(){

public void handleMessage(android.os.Message msg) {

if(msg.what==0x123){

Bitmap bitmap=(Bitmap) msg.obj;

iv.setImageBitmap(bitmap);

}

else if(msg.what==0x124){

String text=(String) msg.obj;

tv.setText(text);

}

};

};

//文本解析

public void click2(View view){

new Thread(){

public void run() {

try {

URL url2=new URL("http://www.baidu.com");

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

conn.setRequestMethod("GET");

conn.setConnectTimeout(8000);

conn.setReadTimeout(8000);

conn.connect();

if(conn.getResponseCode()==200){

InputStream inputStream=conn.getInputStream();

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

byte[]b=new byte[512];

int len;

while ((len=inputStream.read(b))!=-1) {

byteArrayOutputStream.write(b,0,len);

}

String text=new String(byteArrayOutputStream.toByteArray(),"UTF-8");

Message msg=Message.obtain();

msg.what=0x124;

msg.obj=text;

handler.sendMessage(msg);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

};

}.start();

}

//图片解析

public void click(View view){

final File file=new File(getCacheDir(),"2.png");

if(file.exists()){

System.out.println("使用缓存");

Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());

iv.setImageBitmap(bitmap);

}else{

new Thread(){

public void run() {

try {

URL url=new URL("http://192.168.207.1:8090/2.png");

System.out.println("使用网络");

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

conn.setRequestMethod("GET");

conn.setConnectTimeout(8000);

conn.setReadTimeout(8000);

conn.connect();

if(200==conn.getResponseCode()){

//正常连接

InputStream is=conn.getInputStream();

//Bitmap bitmap=BitmapFactory.decodeStream(is);

FileOutputStream fileOutputStream=new FileOutputStream(file);

int len;

byte[] b=new byte[1024];

while ((len=is.read(b))!=-1) {

fileOutputStream.write(b,0,len);

}

fileOutputStream.close();

Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());

fileOutputStream.flush();

Message msg=Message.obtain();

msg.what=0x123;

msg.obj=bitmap;

handler.sendMessage(msg);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

};

}.start();

}

}

}

附:完整实例代码点击此处本站下载。

希望本文所述对大家Android程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值