簡體   English   中英

從Android手機中調用基於JSON的ASP.NET Web服務

[英]Calling a JSON based ASP.NET web-service from an Android phone

我有兩個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代碼。

謝謝

您可以嘗試刪除數據參數中的引號,如下所示:

$.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);}});

希望有幫助!

大聲笑我也找到了答案:),可能是我提出問題的方式不正確,因為我知道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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM