0

嗨朋友们,我是黑莓编程新手,在使 HTTPConnection 向 php Web 服务发送 GET 请求时遇到问题,以下是我正在尝试的代码,

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

请建议我解决方案,谢谢

看待。

4

2 回答 2

1

对不起,我的声誉不允许我发表评论。我的猜测是:您无法连接到 localhost,因此响应代码与 HTTP_OK 不同,因此输入流“in”永远不会被打开,并且当流即将在 finally 中关闭时变量“in”仍然为空-堵塞。因此出现 NullPointerException。

尝试if (in != null) in.close();改用。

于 2011-06-16T12:13:52.733 回答
1

几点评论:

  • 如果您使用的是 OS 5.0+,请改用网络 API。有关更多详细信息,请参阅此答案
  • 您无法从 BlackBerry 连接到 localhost。
  • 使用IOUtilities.streamToBytes而不是 while 循环将数据读取到字节数组。
于 2011-06-16T10:42:57.010 回答