【问题标题】:Calling a JSON based ASP.NET web-service from an Android phone从 Android 手机调用基于 JSON 的 ASP.NET Web 服务
【发布时间】:2015-06-17 18:45:22
【问题描述】:

我有两个 api 方法,它们都可以完美地与 ajax jquery 调用一起工作,但是当我从 android Http 代码调用这两个方法时,第一个方法工作得很好,而另一个没有工作

调用 jquery 的第一个方法示例

 $.ajax({
    type: "POST",
    url: 'websiteaddress/Accounts/Login?username=test&password=test',
    data: '',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) { alert(success);},
    error: function (reponse) { alert(reponse);}
});

调用jquery的第二个方法的例子

 $.ajax({
    type: "POST",
    url: 'websiteaddress/Accounts/Login',
    data: '{username: "test" , password: "test" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) { alert(success);},
    error: function (reponse) { alert(reponse);}
});

实际上我的问题与android有关,但我分享了jquery调用,因为它的代码大小小于android :)

两种调用的主要区别是第一个用 URL 发送数据,第二个用正文发送数据。

希望你能理解我的问题。任何建议将不胜感激。 如果需要,我会分享android代码。

谢谢

【问题讨论】:

    标签: java android jquery json asp.net-web-api


    【解决方案1】:

    您可以尝试删除数据参数中的引号,如下所示:

    $.ajax({
     type: "POST",
     url: 'websiteaddress/Accounts/Login',
     data: {username: "test" , password: "test" },
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (data) { alert(success);},
     error: function (reponse) { alert(reponse);}});
    

    希望有所帮助!

    【讨论】:

    • 您是否阅读到问题结束 :) ?我要求的 android 代码将采用不在 URL 或 Querystring 中的参数
    【解决方案2】:

    lolx 我也找到了答案 :),可能是我提出问题的方式不正确,因为我知道 stackoverflow 上有很多天才开发人员;)可以回答任何与编程相关的问题。

    解决方案很简单。

    JSONObject data = new JSONObject();
    data.put("username", "test");
    data.put("password", "password");
    StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8);
    httpPost.setEntity(entity);
    // Making the call.
    HttpResponse response = httpClient.execute(httpPost);
    

    好吧,我使用的是其他代码,示例如下。

    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("username", "test"));
    parameters.add(new BasicNameValuePair("password", "test"));
    
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
    httpPost.setEntity(entity);
    httpPost.addHeader("content-type", "application/json");
    HttpResponse httpResponse = httpClient.execute(httpPost);
    

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 2011-03-31
      • 1970-01-01
      相关资源
      最近更新 更多