1

我正在 J2ME 中开发基于 GPS 的应用程序。我是 Google API 编码的新手。当我发出一个又一个地图的命令时,例如向上、向下、缩放、缩小,Google 静态地图 API 在此代码处给了我以下错误 - inputStream = connection.openInputStream();

java.io.IOException:没有可用的响应条目

空值

at com.sun.midp.io.InternalConnector.openPrim(+157)
at com.sun.midp.io.InternalConnector.openInternal(+9)
at com.sun.midp.io.j2me.http.Protocol.connect_wap(+210)
at com.sun.midp.io.j2me.http.Protocol.connect(+107)
at com.sun.midp.io.j2me.http.Protocol.openInputStream(+64)
at midletgps.GoogleMaps.run(GoogleMaps.java:90)

这个错误是什么意思&我应该如何解决?请帮助我..因为这个问题我被困在这里......

我的连接代码如下:

//the query string for the Google service
String url = "http://maps.google.com/maps/api/staticmap?center=";
url += latitude + "," + longitude;
url += "&zoom=" + String.valueOf(zoom);
url += "&size=" + width + "x" + height + "&maptype=hybrid" +"&sensor=true" + "&key=API key";
try 
{
    connection = (HttpConnection)Connector.open(url);
    connection.setRequestMethod(HttpConnection.GET);
    inputStream = connection.openInputStream();
    map = Image.createImage(inputStream);
    setImage(map);
    iserror=false;
    repaint();
    midGPS.displayMap();
} 
catch (Exception ex) 
{        
    iserror=true;
    ex.printStackTrace();
}
finally
{
    try 
    {
        if (connection != null) 
        {
             connection.close();
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

我按照所说的方式开发了一个代码,但问题仍然存在。代码是

    String url = "http://maps.googleapis.com/maps/api/staticmap?center=";
    url += latitude + "," + longitude;
    url += "&zoom=" + String.valueOf(zoom);
    url += "&size=" + width + "x" + height + "&maptype=hybrid" +"&sensor=true" + "&key=API key";
    try 
    {
        Image logo = null;
        byte[] imagedata;`

        connection = (ContentConnection)Connector.open(url);
        inputStream = connection.openDataInputStream();

        int len = (int) connection.getLength();
        if(len != -1)
        {
            imagedata = new byte[len]; 

            //get the image into byte 
            inputStream.readFully(imagedata);
        }
        else //length not available 
        {
            byteArray = new ByteArrayOutputStream();
            int c;
            while ((c = inputStream.read()) != -1) 
            {
               byteArray.write(c);
            }   
            imagedata = byteArray.toByteArray();
            byteArray.close();
        }

        //create an Image object
        logo = Image.createImage(imagedata, 0, imagedata.length);
        setImage(logo);
        iserror=false;
        repaint();
        midGPS.displayMap();
    } 
    catch (Exception ex) 
    {        
        iserror=true;
        ex.printStackTrace();
        //showError("Error message : " + ex.getMessage());
    }
    finally
    {
        try 
        {
              if (connection != null) 
              {
                   connection.close();
              }
                      if (inputStream != null) 
              {
                   inputStream.close();
              }
                      if (byteArray != null) 
              {
                   connection.close();
              }
        }
        catch (Exception ex)
        {
            showError("Error message : " + ex.getMessage());
    }
}

我的谷歌地图完整代码如下 -

public class GoogleMaps extends Canvas implements CommandListener, Runnable 

{

    //get the width and the height of the screen

    int width = getWidth();
    int height = getHeight();           
    Image map;
    Command cmdBack = new Command("Back", Command.EXIT, 1);
    Command cmdRefresh = new Command("Refresh", Command.SCREEN, 1);
    MidletGPS midGPS; //reference to the parent MIDlet 
    int zoom = 17;   
    String latitude = "";
    String longitude = "";
    ContentConnection connection = null;
    DataInputStream inputStream = null; 
    ByteArrayOutputStream byteArray = null;
    Thread t;
    boolean iserror = true;
    Alert error;`

    public GoogleMaps(MidletGPS mGPS, String Lat, String Longit) 
    {
    //only for testing    
    latitude = "19.021531";    
    longitude = "72.848432";
    //latitude = Lat;
    //longitude = Longit; 
    midGPS = mGPS;
        this.addCommand(cmdBack);
        this.addCommand(cmdRefresh);
        this.setCommandListener(this);
        runThread();
    }   

    public void runThread()
    {
        t = new Thread(this);
        t.start();
    }

    public void setImage(Image image)
    {
        map = image;
    }
    public void paint(Graphics g) 
    {
       //Paints only, if the search succeeded in returning a location
        if(!iserror) 
        {
            g.drawImage(map, width/2, height/2, Graphics.HCENTER | Graphics.VCENTER);
        }
    }

    public void commandAction(Command c, Displayable d) 
    {
        if (c == cmdBack) 
    {
         midGPS.setCurrentForm(midGPS.mainForm);
    }
    if (c == cmdRefresh) 
    {
            runThread();
        this.repaint();
    }
    }   

    public void run()
    {   

        //the query string for the Google service
    String url = "http://maps.googleapis.com/maps/api/staticmap?center=";
    url += latitude + "," + longitude;
    url += "&zoom=" + String.valueOf(zoom);
    url += "&size=" + width + "x" + height + "&maptype=hybrid" +"&sensor=true" + "&key=API KEY";
    try 
        {
            Image logo = null;
            byte[] imagedata;

            connection = (ContentConnection)Connector.open(url);
            if(inputStream.read() != -1)
            {
                inputStream = connection.openDataInputStream();
            }
            else
            {

            }

            int len = (int) connection.getLength();
            if(len != -1)
            {
                imagedata = new byte[len]; 

                //get the image into byte 
                inputStream.readFully(imagedata);
            }
            else //length not available 
            {
                byteArray = new ByteArrayOutputStream();
                int c;
        while ((c = inputStream.read()) != -1) 
                {
                   byteArray.write(c);
        }   
                imagedata = byteArray.toByteArray();
                byteArray.close();
            }

            //create an Image object
            logo = Image.createImage(imagedata, 0, imagedata.length);
            setImage(logo);
            iserror=false;
            repaint();
            midGPS.displayMap();
        } 
        catch (Exception ex) 
        {        
            iserror=true;
            ex.printStackTrace();
            //showError("Error message : " + ex.getMessage());
    }
    finally
    {
            try 
        {
        if (connection != null) 
        {
            connection.close();
        }
                if (inputStream != null) 
        {
            inputStream.close();
        }
                if (byteArray != null) 
        {
            byteArray.close();
        }
            }
        catch (Exception ex)
            {
                showError("Error message : " + ex.getMessage());
        }
    }
    }

    protected void keyPressed(int keyCode)
    {
        if (((char) keyCode) == '1') 
        {
       zoom--;    
    }
    if (((char) keyCode) == '3')
        {
       zoom++;  
    }
    //if you want to move the map in all directions
    double offset = 0.02;
    if (getGameAction(keyCode) == 5)
        {
            double lon = (Double.parseDouble(longitude));
            lon += offset / zoom;
        longitude = String.valueOf(lon);
        }
    if (getGameAction(keyCode) == 2) 
        {
        double lon = (Double.parseDouble(longitude));
        lon -= offset / zoom;
        longitude = String.valueOf(lon);
    }
    if (getGameAction(keyCode) == 4) 
        {
        double lat = (Double.parseDouble(latitude));
        lat += offset / zoom;
        latitude = String.valueOf(lat);
    }
    if (getGameAction(keyCode) == 6)
        {
        double lat = (Double.parseDouble(latitude));
        lat -= offset / zoom;
        latitude = String.valueOf(lat);
    }

        // re-Call connection thread 
        runThread();

    //call the paint event
    //this.repaint();
     }

    void showError(String message)
    {
    error = new Alert("Error", message, null, AlertType.ERROR);
        error.setTimeout(error.getDefaultTimeout());
    Display.getDisplay(midGPS).setCurrent(error, midGPS.mainForm);
    }
}
4

1 回答 1

1

这是我将如何调试它:

1.首先,确保复制整个 URL 字符串(包括坐标和 API 密钥,我无法为您再次检查),然后将 URL 粘贴到桌面浏览器中。首先,确保您可以通过这种方式检索图像。如果不是,则您的 URL 是错误的。

2.如果步骤 (1) 有效,我会尝试使用以下几种方法检查您的请求状态:

connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
if (connection.getResponseCode() == HttpConnection.HTTP_OK) { // check HTTP code
   inputStream = connection.openInputStream();
   int len = (int) connection.getLength();  
   if (len > 0) {                              // check content length
       map = Image.createImage(inputStream);

确保 HTTP 响应代码看起来正常,并且流打开,产生一个正的内容长度。根据您显示的堆栈跟踪,您的代码可能无法通过长度检查,但它可能对调试很有用......而且总是可能存在不止一个问题。

3.如果您仍然卡住,您可以尝试代码的替代实现来检索 URL 并将其加载到Image对象中。请注意,流和连接在此方法中是局部变量,因此可以在方法结束后的某个时间进行垃圾回收。

private Image getImage(String url) throws IOException
{
    ContentConnection connection = (ContentConnection) Connector.open(url);

    DataInputStream iStrm = connection.openDataInputStream();
    ByteArrayOutputStream bStrm = null;
    Image im = null;

    try
    {
      // ContentConnection includes a length method
      byte imageData[];
      int length = (int) connection.getLength();
      if (length != -1)
      {
        imageData = new byte[length];

        // Read the png into an array
        iStrm.readFully(imageData);
      }
      else  // Length not available...
      {
        bStrm = new ByteArrayOutputStream();

        int ch;
        while ((ch = iStrm.read()) != -1)
          bStrm.write(ch);

        imageData = bStrm.toByteArray();
        bStrm.close();
      }

      // Create the image from the byte array
      im = Image.createImage(imageData, 0, imageData.length);
    }
    finally
    {
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (connection != null)
        connection.close();
      if (bStrm != null)
        bStrm.close();
    }
    return (im == null ? null : im);
} 

更新:另外,请查看此 Nokia J2ME 文档以使用 REST Maps API。请注意此警告:

这里的重点是确保无论请求成功还是失败,所有连接都已关闭。未能执行此基本内务处理会导致连接在几次请求后失败,并出现“没有可用的响应条目”错误。一旦接收到图像,它将作为静态图像保存在 im 对象中。

因此,如果您要保留原始代码,请确保在您的代码finally块中执行此操作:

finally {
    try {
        if (inputStream != null) 
             inputStream.close();

        if (connection != null) 
             connection.close();           
    } catch (Exception ex) {
        ex.printStackTrace();
    }
于 2013-02-01T11:27:41.277 回答