2017-04-05 201 views
2

我正在對休息服務執行HttpPost以撤消許可證。在Android上,請求完美運行。HttpPost在C#中無法正常工作,但在Android中正常工作

@Override 
protected String doInBackground(String... params) 
{ 
     String request = serverUrl + "api/Public/RemoveInstall?DeviceID="+deviceId+"&UserID="+m_userID; 
     try { 
      if(!isNetworkAvailable()) 
      { 
       return "no_accesToken"; 
      } 
      else 
      { 
       URL url = new URL(request); 
       HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
       conn.setConnectTimeout(CONNECTION_TIMEOUT); 
       conn.setDoOutput(false); 
       conn.setInstanceFollowRedirects(false); 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       conn.setRequestProperty("charset", "utf-8"); 
       conn.setConnectTimeout(1500); 
       conn.setUseCaches(false); 
       conn.connect(); 

       ... 
} 

上面的代碼:但這樣做在C#中的帖子的時候,我得到的迴應

在Android中「沒有行動的請求匹配的控制器上找到」完美的作品,但在C#它不會工作:

public async Task<bool> RevokeLicenseAsync(string userId) 
{ 
     if (!IsInternetConnected()) 
     { 
      errorMsg = "No internet connection"; 
      return false; 
     } 

     string deviceId = GetDeviceID(); 

     var postData = new List<KeyValuePair<string, string>>(); 
     postData.Add(new KeyValuePair<string, string>("DeviceID", deviceId)); 
     postData.Add(new KeyValuePair<string, string>("UserID", userId)); 

     //the header arguments "ContentType" and "ContentLength are filled in automatically" 
     var formContent = new FormUrlEncodedContent(postData); 

     if (!String.IsNullOrEmpty(token)) 
     { 
      using (HttpClient httpClient = new HttpClient()) 
      { 
       httpClient.BaseAddress = new Uri(serverUrl); 

       using (var response = await httpClient.PostAsync("api/Public/RemoveInstall",formContent)) 
       { 
+0

第二個具有'=的'的DeviceID在POST,而不是GET –

+0

在您發佈的URL的參數機器人請求,但第二個,你將它張貼在體內。如果第一個工作,然後對第二個工作也一樣。 – Nkosi

+0

噢好吧我會考慮它感謝 – PrisonMike

回答

0

在你的網址,但在第二個發佈參數android的請求,你在身體張貼。

如果第一個工作,然後嘗試做相同的第二個。

var requestUri = string.Format("api/Public/RemoveInstall?DeviceID={0}&UserID={1}", deviceId, userId); 
var request = new HttpRequestMessage(HttpMethod.Post, requestUri); 
using (var httpClient = new HttpClient()) { 
    httpClient.BaseAddress = new Uri(serverUrl); 
    using (var response = await httpClient.SendAsync(request)) { 
     //...other code 
+0

非常感謝您提供簡短而具體的答案 – PrisonMike

+0

什麼時候應該將參數放在身體而不是頭部?這是因爲如果將參數放在主體中,參數將被ssl加密? – PrisonMike

+0

@PrisonMike,這是一個非常廣泛的話題。我也確信這個答案已經在網站上。我的回答僅針對最初發布的問題,即您嘗試使用兩種不同方法訪問服務的問題。 – Nkosi

1

你可以改變如下

public async Task<bool> RevokeLicenseAsync([FromBody]string userId), 

,如果你做一個類型參數post請求,你必須指定FromBody或FormUri

+0

當我嘗試那樣做時出現編譯器錯誤 – PrisonMike

+0

編譯器錯誤的細節是什麼? –

相關問題