2011-06-16 79 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