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 ;
}
}