Android之使用HttpURLConnection进行网络编程

来源:互联网 发布:c语言手册chm 编辑:程序博客网 时间:2024/06/04 17:56

——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)依次创建,启动多条线程来下载网络资源的指定部分

注意需要的权限:

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

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

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

编程步骤如下:

1.先写布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="click"        android:text="加载图片"         />    <ImageView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:id="@+id/iv"/>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="click2"        android:text="加载文本"         />    <TextView         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/tv"/></LinearLayout>
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 blocke.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 blocke.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;@Overrideprotected 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 blocke.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 blocke.printStackTrace();}};}.start();}}}


想要项目的:http://download.csdn.net/detail/qq_33642117/9584014

免费~

0 0
原创粉丝点击