当从远程服务器读取图像时,本地连接在120000之后超时

时间:2011-12-08 09:29:09

标签: blackberry

我正在开发BlackBerry 5.0中的应用程序,并希望显示来自网址的图像。在使用httpconnection从url读取图像时,我得到异常“120000之后本地连接超时”

“httpConnection.getResponseCode()”行上发生异常。

我的代码如下:

private byte[] getimagefromurl(String PhotoUrl)
{

   String url = "http://www.mywebsite.com/images/Folder/xyz.jpg";
   try 
   {
        httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
         System.out.println("url>>>>>>>> "+url);
        httpConnection.setRequestMethod(HttpConnection.GET);
         System.out.println("Response>>>>>>>> "+String.valueOf(httpConnection.getResponseCode()));
        if(httpConnection.getResponseCode() == HttpConnection.HTTP_OK) 
        {

            InputStream input = httpConnection.openInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int j = 0;
            while((j=input.read()) != -1)
            {
                baos.write(j);
            }
            byteArray = baos.toByteArray();
            baos.close();

        }    
   }
   catch(Exception e)
   {
       System.out.println("in catch>>>>"+e.toString());
   }
   return byteArray;               
}

2 个答案:

答案 0 :(得分:2)

当您使用WIFI

时,

追加url扩展名,例如以下示例

 httpConnection = (HttpConnection) Connector.open(url+";interface=wifi", Connector.READ_WRITE);

扩展程序只需检查此网址即可 connection extensions

答案 1 :(得分:1)

是的答案正是如此。连接超时。检查您的网络服务是否有效。如果您要从设备或模拟器进行测试,请确保您可以从默认的黑莓浏览器中点击URL。

如果您在模拟器中进行测试,请确保已启动MDS-CS模拟器。

看看这段有用的代码

import java.io.InputStream; 
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class HTTPClient {
  public static String getPage(String url) {
    String response = "";

    try {
        StreamConnection s = (StreamConnection)Connector.open(url);

        InputStream input = s.openInputStream();

        byte[] data = new byte[256];
        int len = 0;
        StringBuffer raw = new StringBuffer();

        while( -1 != (len = input.read(data))) {
            raw.append(new String(data, 0, len));
        }

        response = raw.toString();

        input.close();
        s.close();
    } catch(Exception e) { }

    return response;
    }
}