Google Static Map API error-java. io. IOException: Aucune Entrée De Réponse Disponible


Je développe une application basée sur le GPS dans J2ME . Je suis nouveau dans le codage de l'API Google. Lorsque je donne la commande de mapper l'un après l'autre, par exemple Haut, Bas, zoom, zoom arrière, l'API Google Static Map me donne l'erreur suivante à ce code - inputStream = connection.openInputStream(); :

Java. io. IOException: Aucune Entrée De réponse disponible

Null

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)

Quelle est la signification de cette erreur et comment dois-je résolu?? Svp aidez-moi.. Je coincé ici à cause de ce problème...

Mon le code de connexion est le suivant:

//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();
    }
}

J'ai développé un code comme dit mais le problème persiste toujours.. Le code est

    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());
    }
}

Mon code complet pour Google maps comme suit -

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);
    }
}
Author: Nate, 2013-02-01

1 answers

Voici comment je déboguerais ceci:

1.Tout d'abord, assurez-vous de copier toute votre chaîne d'URL (y compris les coordonnées et la clé API que je ne peux pas vérifier pour vous), et collez l'URL dans un navigateur desktop. Tout d'abord, assurez-vous que vous pouvez récupérer l'image de cette façon. Sinon, votre URL est mauvaise.

2. Si step (1) fonctionne, j'essaierais de vérifier l'état de votre demande en utilisant quelques méthodes:

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);

Assurez-vous que le code de réponse HTTP semble CORRECT, et le flux s'ouvre, donnant une longueur de contenu positive. Votre code ne parviendra probablement pas à la vérification de la longueur, en fonction de la trace de pile que vous affichez, mais cela pourrait être un débogage utile ... et il pourrait toujours y avoir plus d'un problème.

3.Si vous êtes toujours bloqué, vous pouvez essayer une implémentation alternative du code pour récupérer une URL et la charger dans un Image objet. Notez que le flux et la connexion sont des variables locales dans cette méthode, et donc peut être ramassé quelque temps après la fin de la méthode.

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);
} 

Mise à jour: jetez également un œil à cette documentation Nokia J2ME pour l'utilisation de l'API REST Maps. Prenez note de cet avertissement:

, Le point important ici est de s'assurer que toutes les connexions sont fermé indépendamment du succès ou de l'échec de la demande. L'échec de ce nettoyage de base entraîne l'échec de la connexion après un peu de demandes avec un " Aucune entrée de réponse disponible" erreur. Une fois un l'image est reçue, elle est maintenue comme une image statique dans l'objet im.

Donc, si vous allez garder votre code d'origine, assurez-vous de le faire dans votre finally bloc:

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

        if (connection != null) 
             connection.close();           
    } catch (Exception ex) {
        ex.printStackTrace();
    }
 1
Author: Nate, 2013-02-05 21:52:24