Android開發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程詳解【附源碼下載】
本文實例講述了Android開發(fā)使用HttpURLConnection進(jìn)行網(wǎng)絡(luò)編程。分享給大家供大家參考,具體如下:
——HttpURLConnection
URLConnection已經(jīng)可以非常方便地與指定站點交換信息,URLConnection下還有一個子類:HttpURLConnection,HttpURLConnection在URLConnection的基礎(chǔ)上進(jìn)行改進(jìn),增加了一些用于操作HTTP資源的便捷方法。
setRequestMethod(String):設(shè)置發(fā)送請求的方法
getResponseCode():獲取服務(wù)器的響應(yīng)代碼
getResponseMessage():獲取服務(wù)器的響應(yīng)消息
a)get請求的代碼:
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);//連接超時的毫秒數(shù)
conn.setReadTimeout(8000);//讀取超時的毫秒數(shù)
b)post請求的代碼
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
c)關(guān)閉連接
if(conn!=null)conn.disconnect();
實現(xiàn)多線程下載的步驟:
a)創(chuàng)建URL對象
b)獲取指定URL對象所指向資源的大小:getContentLength()
c)在本地磁盤上創(chuàng)建一個與網(wǎng)絡(luò)資源相同大小的空文件
d)計算每條線程應(yīng)用下載網(wǎng)絡(luò)資源的指定部分
e)依次創(chuà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中文本解析的實現(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中圖片解析的實現(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();
}
}
這個圖片解析實現(xiàn)了圖片的緩存,想要再一次加載圖片的時候,就可以到緩存的文件中得到圖片,就可以減少內(nèi)存的使用~
這個圖片我是放在服務(wù)器端的這個目錄下\apache-tomcat-7.0.37\webapps\upload,從服務(wù)器上可以下載這個圖片,然后保存在文件中~
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();
}
}
}
附:完整實例代碼點擊此處本站下載。
更多關(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é)》
希望本文所述對大家Android程序設(shè)計有所幫助。
- Android開發(fā)使用json實現(xiàn)服務(wù)器與客戶端數(shù)據(jù)的交互功能示例
- Android實現(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類的文件下載實例代碼
- Android網(wǎng)絡(luò)技術(shù)HttpURLConnection詳解
- Kotlin HttpURLConnection與服務(wù)器交互實現(xiàn)方法詳解
相關(guān)文章
Android中實現(xiàn)長按照片彈出右鍵菜單功能的實例代碼
這篇文章主要介紹了Android中實現(xiàn)長按照片彈出右鍵菜單功能,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01
Eclipse開發(fā)環(huán)境導(dǎo)入android sdk的sample中的源碼
初學(xué)Android編程,Android SDK中提供的Sample代碼自然是最好的學(xué)習(xí)材料,需要的朋友可以參考下2012-12-12
Android彈出DatePickerDialog并獲取值的方法
這篇文章主要為大家詳細(xì)介紹了Android彈出DatePickerDialog并獲取值的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05
Android實現(xiàn)加載狀態(tài)視圖切換效果
這篇文章主要為大家詳細(xì)介紹了Android實現(xiàn)加載狀態(tài)視圖切換效果的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07

