【发布时间】:2012-03-15 13:09:28
【问题描述】:
您好,我在 Android 中遇到了一个奇怪的 HTTP 问题。 我正在尝试从远程服务器获取图片并将其显示在设备上。 如果图片是小JPEG,这不是问题。但是如果图片变大就不行了(只显示图片的一部分)。
这是我的完整演示代码:
public class HTTP_testActivity extends Activity {
private ImageView ivPicture;
private Button btGetImage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPicture = (ImageView) findViewById(R.id.ivpiture1);
btGetImage = (Button) findViewById(R.id.btGetPicture1);
btGetImage.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View arg0)
{
URI uri;
try {
uri = new URI("");
URLConnection connection = uri.toURL().openConnection();
connection.setUseCaches(true);
connection.connect();
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
Log.d("TEST","Length of Input " +bis.available());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("TEST","Length of Input after wait " +bis.available());
byte[] data = new byte[640*480*5];
bis.read(data);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, jdata.length);
if (bmp != null)
{
ivPicture.setImageBitmap(bmp);
}
bis.close();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
Log.d("TEST", e.getMessage());
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.d("TEST", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("TEST", e.getMessage());
e.printStackTrace();
}
}
});
}
有人能看出我做错了什么吗? 到目前为止我发现的是: bis.available() 返回的大小永远不会超过 65kb。尽管 InputStream 本身具有正确的长度(在调试器中看到)。
【问题讨论】:
-
请不要在 UI 线程上进行网络 I/O。当服务器变得有点太慢时,您的应用程序将被操作系统强制关闭。 Andriod上有很多关于如何异步处理网络的教程。
-
如果您实际阅读了可用的数量 bis 报告,那么 bis.available() 是否会报告更多可用?换句话说,您是否考虑过 while (bis.available() > 0) 循环?除非您事先知道所需的大小,否则您可能需要稍微调整字节缓冲区,在这种情况下,您可以创建足够大的缓冲区以开始并简单地使用每次读取都会增加的起始偏移量。
标签: java android http image http-get