http用於傳輸WWW方式的數據。http協議采用了請求響應的模型。在Android中提供了HttpURLConnection和HttpClient接口開發HTTP程序。下面分別使用這兩種方式獲取網絡圖片。
1.HttpURLConnection
代碼如下:
[html]
- public class HttpURLConnectionActivity extends Activity {
-
- private ImageView imageView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.simple1);
-
- imageView=(ImageView) this.findViewById(R.id.imageView1);
- //傳入網絡圖片地址
- try {
- URL url = new URL("http://news.xinhuanet.com/photo/2012-02/09/122675973_51n.jpg");
- HttpURLConnection conn= (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(5*1000);
- conn.connect();
- InputStream in=conn.getInputStream();
- ByteArrayOutputStream bos=new ByteArrayOutputStream();
- byte[] buffer=new byte[1024];
- int len = 0;
- while((len=in.read(buffer))!=-1){
- bos.write(buffer,0,len);
- }
- byte[] dataImage=bos.toByteArray();
- bos.close();
- in.close();
- Bitmap bitmap=BitmapFactory.decodeByteArray(dataImage, 0, dataImage.length);
- //Drawable drawable=BitmapDrawable.
- imageView.setImageBitmap(bitmap);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- Toast.makeText(getApplicationContext(), "圖片加載失敗", 1).show();
- }
-
- }
- }
最後不要忘記在manifest.xml加入網絡訪問權限:
[html]
- <uses-permission android:name="android.permission.INTERNET" />
由於訪問網絡圖片是比較耗時的操作,所以在正式項目中使用異步加載圖片,效果會更好。
運行效果:
2.HttpClient
下面使用HttpClient獲取網頁內容:
[html]
- public class HttpClientActivity extends Activity {
-
- private ImageView imageview;
- private TextView text;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.simple2);
-
- imageview=(ImageView) this.findViewById(R.id.imageView2);
- text=(TextView) this.findViewById(R.id.textView2);
- HttpGet httpGet=new HttpGet("http://cloud.csdn.net/a/20120209/311628.html");
- HttpClient httpClient=new DefaultHttpClient();
- try {
- //得到HttpResponse對象
- HttpResponse httpResponse=httpClient.execute(httpGet);
- //HttpResponse的返回結果是不是成功
- if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
- //得到返回數據的字符串
- String dataImageStr=EntityUtils.toString(httpResponse.getEntity());
- text.setText(dataImageStr);
- }
- } catch (ClientProtocolException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
運行效果:
這樣就成功加載了網頁內容。