作爲職場小白,在做android 整機app, Camera和Gallery. 但是對android 網絡編程理解不是很深,所以從這篇文章開始我的網絡學習之旅。
首先先通過一個例子來看如何下載一張圖片的。
本例子使用的是AsyncTask進行異步操作的。
分析步驟:
(1) 如何使用HttpURLConnection進行網絡連接
url = new URL("http://f.hiphotos.baidu.com/image/w%3D2048/sign=3b06d28fc91349547e1eef6462769358/d000baa1cd11728b22c9e62ccafcc3cec2fd2cd3.jpg");
huc = (HttpURLConnection) url.openConnection(); //根據url生成的HttpURLConnection對象,此時還沒開始連接網絡
int code = huc.getResponseCode(); //http狀態返回代碼
一般常見的狀態返回代碼爲:
404 - 請求的網頁不存在
503 - 服務不可用
(2) 如何獲得訪問網址的資源
InputStream is = huc.getInputStream();
一般使用連接時候,使用huc.connect(); 而getInputStream()中就已經包含了connect()方法,所以此時可省略。
當執行完這句話的時候,圖片數據已經保存在輸入流中。
(3) 對流進行存儲並轉化成bitmap進行使用,記得對bitmap進行釋放。
if (code == 200) {
InputStream is = huc.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
is.close();
output.close();
byte[] bytes = output.toByteArray();
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
因爲代碼簡單這裏就直接上源碼了,本來準備輸入網址在下載,發現網址太長,就改成了在代碼中直接寫了。
package com.example.hoperun.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 知道固定圖片網址,下載圖片demo
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText urlText = null;
private ImageView imageView = null;
private Button clickButton = null;
private SearchImageAsyncTask siat = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
urlText = (EditText) findViewById(R.id.urlText);
clickButton = (Button) findViewById(R.id.clickMe);
clickButton.setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.imageView);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.clickMe:
if (!TextUtils.isEmpty(urlText.getText().toString())) {
siat = new SearchImageAsyncTask();
siat.execute(urlText.getText().toString());
} else {
Toast.makeText(MainActivity.this, "請輸入網址", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
public class SearchImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
private URL url = null;
private HttpURLConnection huc = null;
Bitmap bitmap = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... strings) {
try {
url = new URL("http://f.hiphotos.baidu.com/image/w%3D2048/sign=3b06d28fc91349547e1eef6462769358/d000baa1cd11728b22c9e62ccafcc3cec2fd2cd3.jpg");
huc = (HttpURLConnection) url.openConnection();
int code = huc.getResponseCode(); //http狀態返回代碼
if (code == 200) {
InputStream is = huc.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
is.close();
output.close();
byte[] bytes = output.toByteArray();
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap); //給imageview設置資源
}
}
}
第一次寫,還不知道預覽起來是什麼樣子,寫的不好請見諒,以後會改進。