2015-04-12 54 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 –