2011-06-16 82 views
0

喜的朋友我是新黑莓编程,我得到的问题,同时使HttpConnection的发送GET请求到PHP的Web服务,下面是我想的代码,黑莓编程和Java ME

HttpConnection conn = null; 
    InputStream in = null; 
    StringBuffer buff = new StringBuffer(); 
    String result = null; 
    String url = "http://localhost/blackberry/locations.php?device_id="+id+"&lat="+lat+"&lon="+lon 
    try{ 
     conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE, true); 
     conn.setRequestMethod(HttpConnection.GET); 
     conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0"); 
     if(conn.getResponseCode() == HttpConnection.HTTP_OK){ 
      in = conn.openInputStream(); 
      int chr; 
      //xp.parse(in, handler); 
      while((chr = in.read()) != -1){ 
       buff.append((char)chr); 
      } 
      result = buff.toString(); 
     } 
     else{ 
      result = "Error in connection"; 
      return result; 
     } 

    } catch(Exception ex){ 
     System.out.println(ex.getMessage()); 
    } finally{ 
     try { 
      in.close(); 
      conn.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

请建议我解决方案, 谢谢

注意。

+0

请问具体问题是什么? – razlebe 2011-06-16 10:40:58

+0

你的问题是什么?有什么异常? – bharath 2011-06-16 10:44:26

+0

我在上面的代码中得到了nullPointerException。 – 2011-06-16 10:51:16

回答

1

几点意见:

  • 如果您使用的是OS 5.0以上,使用网络API来代替。有关详细信息,请参阅this answer
  • 您无法从BlackBerry连接到本地主机。使用IOUtilities.streamToBytes代替while循环将数据读取到字节数组。
1

对不起,我的声誉不允许我发表评论。我的猜测是:你不能连接到本地主机,因此响应代码与HTTP_OK不同,因此输入流'in'永远不会被打开,并且当流将在finally中被关闭时变量'in'仍然为空,块。因此NullPointerException。

尝试使用if (in != null) in.close();代替。

+0

现在我使用的IP地址,而不是本地主机仍然得到相同的nullpointerexception – 2011-06-16 13:07:56