国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android開發使用HttpURLConnection進行網絡編程詳解【附源碼下載】

2019-10-22 18:16:09
字體:
來源:轉載
供稿:網友

本文實例講述了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"/>

更多關于Android權限控制的說明可參考Android Manifest功能與權限描述大全

這里我簡單的使用一下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程序設計有所幫助。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黄浦区| 克什克腾旗| 峨山| 瓮安县| 肇源县| 清水河县| 慈利县| 牟定县| 大洼县| 子洲县| 元阳县| 茂名市| 三都| 忻州市| 崇文区| 广丰县| 辽阳县| 台中市| 黄石市| 行唐县| 巴彦淖尔市| 远安县| 铁力市| 彭州市| 忻州市| 毕节市| 鄂托克旗| 安多县| 乃东县| 定结县| 黄梅县| 筠连县| 峨眉山市| 财经| 石河子市| 浦城县| 辛集市| 寿宁县| 涪陵区| 略阳县| 白河县|