2009-07-29 115 views
4

我需要一些帮助。使用JME(或J2ME)消费REST服务

我需要知道如何调用REST服务解析xml

我的PHP脚本只发回一些xmlcode,仅此而已。(没有WSDL和UDDI)

平台诺基亚5800 S60第三版。(一个将适用) 诺基亚sdk去了相同的名字。 我为这个项目安装了Netbeans。

唯一的东西,我觉得是soap based

为此我可以使用哪些方法/库?我不得不提到,我也是java/netbeans的新手。

+0

实际上,诺基亚5800的平台是Series60 FIFTH版本,但这对你的问题没有关系 – 2009-07-30 18:58:51

+0

是的,你是对的,除了我只能找到sdk第三版。 我不确定如何处理它,但我会发现。 – Richard 2009-07-31 14:26:14

回答

9

要调用REST Web服务可以使用HttpConnection类:

HttpConnection connection = null; 
InputStream is = null; 

final ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

byte[] response = null; 

try { 
    connection = (HttpConnection)Connector.open("http://api.yourserver.com/rest/things/12", Connector.READ); 
    connection.setRequestMethod(HttpConnection.GET); 

    connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1"); 

    if (connection.getResponseCode() == HttpConnection.HTTP_OK) { 
     is = connection.openInputStream(); 

     if (is != null) { 
      int ch = -1; 

      while ((ch = is.read()) != -1) { 
       bos.write(ch); 
      } 

      response = bos.toByteArray(); 
     } 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (bos != null) { 
      bos.close(); 
      bos = null; 
     } 

     if (is != null) { 
      is.close(); 
      is = null; 
     } 

     if (connection != null) { 
      connection.close(); 
      connection = null; 
     } 
    } catch (Exception e2) { 
     e2.printStackTrace(); 
    } 
} 

现在响应将包含您的服务器吐出XML。您可以使用kXML2库来解析它。请注意,该库引用了XMLPull库,因此您必须将其包含在您的项目中。

2

我正在使用REST,并且使用JSONObject和JSONArrays来处理Java ME中的Mobile Ajax。在REST上工作是一种简单的方法,库需要以源代码格式下载并使用Netbeans或ANT进行编译,这很容易,只需通过SVN检查项目并在网页(WithXML或WithoutXML)中进行构建即可是使用REST和雅虎地图等公共Web服务的样本!我希望你喜欢它。