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

作者:飘走的我 时间:2022-01-11 23:27:37 

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

注意需要的权限:


<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 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程序设计有所帮助。

来源:http://blog.csdn.net/qq_33642117/article/details/52003278

标签:Android,HttpURLConnection
0
投稿

猜你喜欢

  • Springboot打成war包并在tomcat中运行的部署方法

    2022-06-29 07:53:32
  • Spring动态配置计时器触发时间的实例代码

    2023-01-20 07:30:01
  • Android通讯录开发之删除功能的实现方法

    2021-07-06 10:43:53
  • 基于自定义Toast全面解析

    2023-08-27 19:18:55
  • Java编程BigDecimal用法实例分享

    2022-05-02 05:40:06
  • Spring框架通过工厂创建Bean的三种方式实现

    2022-11-23 11:29:54
  • SpringBoot项目从搭建到发布一条龙

    2023-11-21 09:28:44
  • Springboot多种情况yml配置代码实例

    2022-05-14 23:26:00
  • C#调用Oracle存储过程的方法

    2022-10-19 02:29:19
  • mybatis-plus分页查询的实现示例

    2023-11-25 04:57:57
  • SpringCache之 @CachePut的使用

    2021-12-06 11:08:31
  • mybatis insert foreach循环插入方式

    2023-10-15 22:32:53
  • Android 自定义View实现单击和双击事件的方法

    2022-03-23 19:21:18
  • 记一次springboot服务凌晨无故宕机问题的解决

    2023-07-25 04:50:23
  • Java 如何实现一个http服务器

    2022-03-27 05:40:04
  • 设置JavaScript自动提示-Eclipse/MyEclipse

    2022-06-15 12:41:05
  • java模拟实现斗地主发牌小程序

    2021-07-20 01:55:11
  • 源码解析JDK 1.8 中的 Map.merge()

    2023-11-16 23:49:25
  • Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup

    2023-02-19 23:22:37
  • java多线程Future和Callable类示例分享

    2021-09-02 09:49:37
  • asp之家 软件编程 m.aspxhome.com