Android開發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程詳解【附源碼下載】
本文實(shí)例講述了Android開發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程。分享給大家供大家參考,具體如下:
——HttpURLConnection
URLConnection已經(jīng)可以非常方便地與指定站點(diǎn)交換信息,URLConnection下還有一個(gè)子類: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)多線程下載的步驟:
a)創(chuàng)建URL對(duì)象
b)獲取指定URL對(duì)象所指向資源的大小:getContentLength()
c)在本地磁盤上創(chuàng)建一個(gè)與網(wǎng)絡(luò)資源相同大小的空文件
d)計(jì)算每條線程應(yīng)用下載網(wǎng)絡(luò)資源的指定部分
e)依次創(chuàng)建,啟動(dòng)多條線程來下載網(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)限控制的說明可參考Android Manifest功能與權(quán)限描述大全
這里我簡單的使用一下HttpURLConnection來進(jìn)行文本解析和圖片解析
編程步驟如下:
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中文本解析的實(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.最后,把文本和圖片加載出來
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("使用網(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)容感興趣的讀者可查看本站專題:《Android通信方式總結(jié)》、《Android開發(fā)入門與進(jìn)階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android開發(fā)使用json實(shí)現(xiàn)服務(wù)器與客戶端數(shù)據(jù)的交互功能示例
- Android實(shí)現(xiàn)與Apache Tomcat服務(wù)器數(shù)據(jù)交互(MySql數(shù)據(jù)庫)
- 詳解Android客戶端與服務(wù)器交互方式
- Android HttpURLConnection下載網(wǎng)絡(luò)圖片設(shè)置系統(tǒng)壁紙
- Android 用HttpURLConnection訪問網(wǎng)絡(luò)的方法
- Android基于HttpUrlConnection類的文件下載實(shí)例代碼
- Android網(wǎng)絡(luò)技術(shù)HttpURLConnection詳解
- Kotlin HttpURLConnection與服務(wù)器交互實(shí)現(xiàn)方法詳解
相關(guān)文章
Android使用個(gè)推實(shí)現(xiàn)三方應(yīng)用的推送功能
這篇文章主要為大家詳細(xì)介紹了Android使用個(gè)推實(shí)現(xiàn)三方應(yīng)用的推送功能,感興趣的小伙伴們可以參考一下2016-08-08Android開發(fā)的IDE、ADT、SDK、JDK、NDK等名詞解釋
這篇文章主要介紹了Android開發(fā)的IDE、ADT、SDK、JDK、NDK等名詞解釋,對(duì)這些概念搞不清楚是一件痛苦的事,本文就簡潔講解了這些名詞的含義,一起掃盲吧,需要的朋友可以參考下2015-06-06Android自定義textview實(shí)現(xiàn)豎直滾動(dòng)跑馬燈效果
這篇文章主要為大家詳細(xì)介紹了Android自定義textview實(shí)現(xiàn)豎直滾動(dòng)跑馬燈效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06Android 將view 轉(zhuǎn)換為Bitmap出現(xiàn)空指針問題解決辦法
這篇文章主要介紹了Android 將view 轉(zhuǎn)換為Bitmap出現(xiàn)空指針問題解決辦法的相關(guān)資料,這里提供實(shí)例并提供解決辦法,需要的朋友可以參考下2017-07-07Android 圖片保存到相冊(cè)不顯示的解決方案(兼容Android 10及更高版本)
這篇文章主要介紹了Android 圖片保存到系統(tǒng)相冊(cè)不顯示的解決方案,幫助大家更好的理解和學(xué)習(xí)使用Android開發(fā),感興趣的朋友可以了解下2021-04-04Android CoordinatorLayout高級(jí)用法之自定義Behavior
這篇文章主要介紹了Android CoordinatorLayout高級(jí)用法之自定義Behavior,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02