2015-04-12 51 views
1

我有两个API方法,他们都与AJAX jquery调用完美工作,但是当我从android Http代码调用这两个方法,第一种方法工作完美的,其他第二不从调用jQuery的从Android手机调用基于JSON的ASP.NET网络服务

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

AC工作

从调用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);} 
}); 

第2种方法的例子

第1种方法的例子其实我的问题是与android有关,但我分享了jquery调用,因为它的代码尺寸小于android :)

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

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

感谢

回答

1

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

希望帮助!

+0

你读到问题结束:)?我要求的Android代码将采取参数不在URL或Querystring –