android 网络编程实现,Android开发使用HttpURLConnection进行网络编程详解【附源码下载】...
本文實例講述了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)依次創建,啟動多條線程來下載網絡資源的指定部分
注意需要的權限:
這里我簡單的使用一下HttpURLConnection來進行文本解析和圖片解析
編程步驟如下:
1.先寫布局文件:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="加載圖片"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="@+id/iv"/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click2"
android:text="加載文本"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"/>
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 网络编程实现,Android开发使用HttpURLConnection进行网络编程详解【附源码下载】...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 摩尔庄园手游烹饪怎么灭火?
- 下一篇: 按摩器多少钱啊?