【问题标题】:Calling Rest webservice in Android在 Android 中调用 Rest web 服务
【发布时间】:2012-11-19 15:16:07
【问题描述】:

我有 Java Web 应用程序服务器 [ 行为类似于服务器 ]。

在 Android 应用程序中,我使用 httppost 调用了 restwebserver 服务器。

我的调用是使用响应代码 200 访问网络服务。

现在我想将 java 类对象作为参数传递。

示例 java 类:

public Class Sample{

public String Username;

public String getUsername()
{

return Username;

}

public void setUsername(String user){


this.Username = user;

}}

使用的代码:[没有将我的类对象传递给服务器]

  Sample sam = new Sample();
  sam.setUsername("Test");
  JSONObject json = new JSONObject();  
  json.put("Sample", sam);            
  StringEntity se = new StringEntity(json.toString());  
  Httppostrequest.setEntity(se);

当我调试服务器时,示例对象参数输入为空。[未正确传递]
如何在android中通过http post传递类对象? 请帮我解决这个问题。

提前致谢,

库姆斯

【问题讨论】:

  • 尽管对象sam 像` jSONObject().put("Sample", "Hello, World!")` AFAIK 你只能在JSON 中使用字符串表示数据.见here
  • 为什么不使用像this这样的REST webservice?

标签: android


【解决方案1】:

如果你使用 apache 库,你可以做到这一点

JSONSerializer.toJSON(sam);

否则我认为您必须将其发送为

 Sample sam = new Sample();
 sam.setUsername("Test");
  JSONObject json = new JSONObject();  
  json.put("sample", sam.getUserName());
StringEntity se = new StringEntity(json.toString());  
 Httppostrequest.setEntity(se);

【讨论】:

    【解决方案2】:

    这是一个代码sn-p

      public void callWebService(String q){  
         HttpClient httpclient = new DefaultHttpClient();  
         HttpGet request = new HttpGet(URL + q);  
         request.addHeader("deviceId", deviceId);  
         ResponseHandler<string> handler = new BasicResponseHandler();  
         try {  
             result = httpclient.execute(request, handler);  
         } catch (ClientProtocolException e) {  
             e.printStackTrace();  
         } catch (IOException e) {  
             e.printStackTrace();  
         }  
         httpclient.getConnectionManager().shutdown();  
         Log.i(tag, result);  
     } // end callWebService()  
    

    }

    使用此方法调用您的网络服务

    【讨论】:

      【解决方案3】:

      我已经建立了一个用于执行异步请求的库,您可以将参数请求发送为 www.somedomain.com/action?param1="somevalue" 等。还有使用字符串正文的选项。

      https://github.com/darko1002001/android-rest-client

      看看吧,也许会有帮助。

      【讨论】:

        猜你喜欢
        • 2017-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 2015-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多