溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Android開(kāi)發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程詳解【附源碼下載】

發(fā)布時(shí)間:2020-08-27 12:00:12 來(lái)源:腳本之家 閱讀:115 作者:飄走的我 欄目:移動(dòng)開(kāi)發(fā)

本文實(shí)例講述了Android開(kāi)發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程。分享給大家供大家參考,具體如下:

——HttpURLConnection

URLConnection已經(jīng)可以非常方便地與指定站點(diǎn)交換信息,URLConnection下還有一個(gè)子類(lèi):HttpURLConnection,HttpURLConnection在URLConnection的基礎(chǔ)上進(jìn)行改進(jìn),增加了一些用于操作HTTP資源的便捷方法。

setRequestMethod(String):設(shè)置發(fā)送請(qǐng)求的方法
getResponseCode():獲取服務(wù)器的響應(yīng)代碼
getResponseMessage():獲取服務(wù)器的響應(yīng)消息

a)get請(qǐng)求的代碼:

conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);//連接超時(shí)的毫秒數(shù)
conn.setReadTimeout(8000);//讀取超時(shí)的毫秒數(shù)

b)post請(qǐng)求的代碼

conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");

c)關(guān)閉連接

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

實(shí)現(xiàn)多線(xiàn)程下載的步驟:

   a)創(chuàng)建URL對(duì)象
   b)獲取指定URL對(duì)象所指向資源的大小:getContentLength()
   c)在本地磁盤(pán)上創(chuàng)建一個(gè)與網(wǎng)絡(luò)資源相同大小的空文件
   d)計(jì)算每條線(xiàn)程應(yīng)用下載網(wǎng)絡(luò)資源的指定部分
   e)依次創(chuàng)建,啟動(dòng)多條線(xiàn)程來(lái)下載網(wǎng)絡(luò)資源的指定部分

注意需要的權(quán)限:

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

更多關(guān)于Android權(quán)限控制的說(shuō)明可參考Android Manifest功能與權(quán)限描述大全

這里我簡(jiǎn)單的使用一下HttpURLConnection來(lái)進(jìn)行文本解析和圖片解析

編程步驟如下:

1.先寫(xiě)布局文件:

<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中文本解析的實(shí)現(xiàn):

//文本解析
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中圖片解析的實(shí)現(xiàn):

//圖片解析
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("使用網(wǎng)絡(luò)");
     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();
 }
}

這個(gè)圖片解析實(shí)現(xiàn)了圖片的緩存,想要再一次加載圖片的時(shí)候,就可以到緩存的文件中得到圖片,就可以減少內(nèi)存的使用~

這個(gè)圖片我是放在服務(wù)器端的這個(gè)目錄下\apache-tomcat-7.0.37\webapps\upload,從服務(wù)器上可以下載這個(gè)圖片,然后保存在文件中~

4.最后,把文本和圖片加載出來(lái)

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);
  }
 };
};

效果圖我就不貼了,知道代碼怎么寫(xiě)就行~

完整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("使用網(wǎng)絡(luò)");
      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();
  }
 }
}

附:完整實(shí)例代碼點(diǎn)擊此處本站下載。

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Android通信方式總結(jié)》、《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android調(diào)試技巧與常見(jiàn)問(wèn)題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》

希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI