使用服务器JSON的Android下载图像 [英] Android download image from server using json
问题描述
我的应用程序包含几个按钮,是通过点击任何按钮,我想要什么,就直接我到一个URL这反过来又带我到要显示上一个JSON对象页面,然后提供给我的图像源我的Android设备。
my application contains few buttons, what i want is by clicking on any of the button, it will direct me to a URL which in turn take me to a json object page which then provide me an image source to be displayed on to my android device.
有关如:按钮1 - > HTTP://abcd/loadview.htm buttonid = B1 一> - > JSON对象(IMG src- URL到图像文件) - >获取显示我的Android设备上
For eg: Button 1 -> http://a.b.c.d/loadview.htm?buttonid=B1 -> Json object(img src- url to image file) -> get displayed on my android device.
在此先感谢:)
推荐答案
这是工作code:可从服务器下载图像和android的显示它
This is working code: To download the image from server and display it in android
public void onCreate(Bundle savedInstanceState)
{
Bitmap bitmap = DownloadImage("http://www.aaa.com/images//29_13.jpeg");
ImageView img = (ImageView) findViewById(R.id.imagefromserver);
img.setImageBitmap(bitmap);
}
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
这篇关于使用服务器JSON的Android下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!