안규 공부방

Android > HttpURLConnection - 서버이미지 불러오기 예제

등록일 : 2017-07-06 17:35 조회수 : 93,561

서버에 있는 이미지를 ImageView 에 뿌리는 예제 입니다.
 
	public class LoadImageServer extends Activity {   
		@Override   
		public void onCreate(Bundle savedInstanceState) {   
			super.onCreate(savedInstanceState);   
			setContentView(R.layout.main);   

			String imagePath	= "http://entersoft.kr/images/1.png" ;   
			ImageView imgView	= (ImageView) findViewById(R.id.imgView) ;   
			Bitmap bm = LoadImage( imagePath ) ; // 이렇게 imagePath만 넣어주면, Bitmap으로 반환이 된다.  
			imgView.setImageBitmap( bm ) ;  // 그 Bitmap을 찍기만 하면 된다. 
		}   

		private Bitmap LoadImage( String imagePath ) { 
			InputStream inputStream = OpenHttpConnection( imagePath ) ;   
			Bitmap bm = BitmapFactory.decodeStream( inputStream ) ;   
			return bm;   
		}   

		private InputStream OpenHttpConnection(String imagePath) {   
			InputStream stream = null ;   
			try {   
				URL url = new URL( imagePath ) ;   
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;   
				urlConnection.setRequestMethod("GET");   
				urlConnection.connect() ;   
				if( urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK ) {   
					stream = urlConnection.getInputStream() ;   
				}   
			} catch (MalformedURLException e) {   
				e.printStackTrace();   
			} catch (IOException e) {   
				e.printStackTrace();   
			}   
			
			return stream ;   
		}   
	}  
	



 
※ 혹시 도움이 되셨다면 댓글에 한마디 남겨주세요!
작성자   비밀번호
자동글 방지     (자동글 방지 기능입니다.)
내용   댓글달기 
이메일 문의 : cak0280@nate.com  
Copyright 2000 By ENTERSOFT.KR All Rights Reserved.