我的应用程序循环通过大约 200 个 url 都是 jpg 图像。在模拟器中它读取正常,然后将字节数组存储在 persistentStore 中,没有问题。在设备上,它给出了 java.io.IOException: TCP read timed out 基本上每个图像。时不时地,一个人通过。甚至不确定如何。图像尺寸也不能提供洞察力。有些是6k,有些是11k。大小似乎对超时无关紧要。
我会尝试发布我认为相关的代码,但我不是这里的专家,所以如果我遗漏了一些东西,请说出来。
通过循环调用http连接并加入线程:
for(int i = 0; i < images.size(); i ++)
{
try {
String url = images.elementAt(i).toString();
HttpRequest data3 = new HttpRequest(url, "GET", false);
data3.start();
data3.join();
} catch (IOException e) {
Dialog.inform("wtf " + e);
}
}
使用正确的后缀在 HttpConnection 类中建立实际连接:
try
{
HttpConnection connection = (HttpConnection)Connector.open(url + updateConnectionSuffix());
int responseCode = connection.getResponseCode();
if(responseCode != HttpConnection.HTTP_OK)
{
connection.close();
return;
}
String contentType = connection.getHeaderField("Content-type");
long length = connection.getLength();
InputStream responseData = connection.openInputStream();
connection.close();
outputFinal(responseData, contentType, length);
}
catch(IOException ex)
{
} catch (SAXException ex) {
} catch (ParserConfigurationException ex) {
}
最后,读取流并将字节写入字节数组:
else if(contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif"))
{
try
{
if((int) length < 1)
length = 15000;
byte[] responseData = new byte[(int) length];
int offset = 0;
int numRead = 0;
StringBuffer rawResponse = new StringBuffer();
int chunk = responseData.length-offset;
if(chunk < 1)
chunk = 1024;
while (offset < length && (numRead=result.read(responseData, offset, chunk)) >= 0){
rawResponse.append(new String(responseData, offset, numRead));
offset += numRead;
}
String resultString = rawResponse.toString();
byte[] dataArray = resultString.getBytes();
result.close();
database db = new database();
db.storeImage(venue_id, dataArray);
}
catch( Exception e )
{
System.out.println(">>>>>>>----------------> total image fail: " + e);
}
}
需要考虑的事项:
长度始终是模拟器中的字节长度。在设备中它总是-1。
chunk var 是一个测试,看看我是否强制使用 15k 字节数组,它是否会尝试按预期读取,因为 byte[-1] 给出了越界异常。结果是一样的。有时会写。主要是超时。
任何帮助表示赞赏。