0

我創建了支持Android和iOS移動平臺的Xamrin原生共享項目。我想在兩個移動應用程序中使用REST服務。如果我使用HttpClient向REST API發出請求,那麼它不起作用。給我的反應是:Xamarin原生共享項目HttpClient不起作用

{的StatusCode:404,ReasonPhrase: '未找到',版本:1.1,內容: System.Net.Http.StreamContent,頭:{有所不同:接受編碼 服務器:DPS /1.0.3 X-SiteId:1000 Set-Cookie:dps_site_id = 1000;路徑=/ 日期:2016年7月27日星期三12:09:00 GMT連接:keep-alive Content-Type:text/html; charset = utf-8 Content-Length:964}} 內容:{System.Net.Http.StreamContent}標題:{Vary: Accept-Encoding Server:DPS/1.0.3 X-SiteId:1000 Set-Cookie: dps_site_id = 1000; path =/Date:Wed,27 Jul 2016 12:09:00 GMT Connection:keep-alive} IsSuccessStatusCode:false ReasonPhrase: 「Not Found」StatusCode:System.Net.HttpStatusCode.NotFound版本:0​​{1.1}公衆會員:

如果我使用HttpWebResponse發出請求,它會成功獲取數據。

您能否說出爲什麼HttpClient不工作?

// Using HttpClient 
    public async Task<string> GetCategories11(string token) 
    { 
     using (HttpClient client = new HttpClient()) 
     { 
      var url = string.Format("{0}{1}", BaseUrl, CategoriesEndPoint); 
      var uri = new Uri(url); 
      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); 
      client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); 
      try 
      { 
       using (var response = await client.GetAsync(uri)) 
       { 
        if (response.IsSuccessStatusCode) 
        { 
         var contentStr = await response.Content.ReadAsStringAsync(); 
         return contentStr; 
        } 
        else 
         return null; 
       } 
      } 
      catch 
      { 
       return null; 
      } 
     } 
    } 

    // Using HttpWebRequest 
    public async Task<ResponseModel> GetCategories(string token) 
    { 
     // Create an HTTP web request using the URL: 
     var url = string.Format("{0}{1}", RequestClient.BaseUrl, CategoriesEndPoint); 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); 
     request.ContentType = "application/json"; 
     request.Headers.Add("Authorization", "Bearer " + token); 
     request.Accept = "application/json"; 
     request.Method = "GET"; 

     try 
     { 
      // Send the request to the server and wait for the response: 
      using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) 
      { 
       // Get a stream representation of the HTTP web response. 
       using (Stream stream = response.GetResponseStream()) 
       { 
        // Use this stream to build a JSON object. 
        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream)); 

        return new ResponseModel() { Success = true, ResponseValue = jsonDoc.ToString(), StatusCode = response.StatusCode }; 
       } 
      } 
     } 
     catch (WebException ex) 
     { 
      using (var stream = ex.Response.GetResponseStream()) 
      using (var reader = new StreamReader(stream)) 
      { 
       return new ResponseModel() { ResponseValue = reader.ReadToEnd(), StatusCode = ((HttpWebResponse)ex.Response).StatusCode }; 
      } 
     } 
     catch (Exception ex) 
     { 
      return new ResponseModel() { ResponseValue = ex.Message }; 
     } 
    } 

回答

0

調試通過,並暫停在線using (var response = await client.GetAsync(uri))是什麼uri?它和GetCategories()中的一樣嗎?

如果您願意,這是我從Xamarin.Android使用的方法,它可以與不記名令牌一起使用。爲適應您的需求而更改,您可能不需要執行JsonConvert.DeserializeObject()部分。

protected async Task<T> GetData<T>(string dataUri, string accessToken = null, string queryString = null) 
{ 
    var url = baseUri + "/" + dataUri + (!string.IsNullOrEmpty(queryString) ? ("?" + queryString) : null); 
    try 
    { 
     using (var httpClient = new HttpClient() { Timeout = new TimeSpan(0, 0, 0, 0, SharedMobileHelper.API_WEB_REQUEST_TIMEOUT) }) 
     { 
      // Set OAuth authentication header 
      if (!string.IsNullOrEmpty(accessToken)) 
       httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 

      using (HttpResponseMessage response = await httpClient.GetAsync(url)) 
      { 
       string content = null; 
       if (response != null && response.Content != null) 
        content = await response.Content.ReadAsStringAsync(); 

       if (response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Created) 
       { 
        if (content.Length > 0) 
         return JsonConvert.DeserializeObject<T>(content); 
       } 
       else if (response.StatusCode == HttpStatusCode.InternalServerError) 
       { 
        throw new Exception("Internal server error received (" + url + "). " + content); 
       } 
       else 
       { 
        throw new Exception("Bad or invalid request received (" + url + "). " + content); 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     Log.Error("Could not fetch data via GetData (" + url + ").", ex.ToString()); 
     throw ex; 
    } 
    return default(T); 
} 
+0

** @ GoNeale,**調試通過,並暫停** 我得到我的下的問題是添加了迴應:「給我的反應是:」了。 **什麼是uri?並且它與GetCategories()中的一樣?** in * HttpClient方法 var uri = new Uri(url); 使用(VAR響應=等待client.GetAsync(URI))* 在* HttpWebRequest的方法 HttpWebRequest的請求=(HttpWebRequest的)HttpWebRequest.Create(新URI(URL)); * 兩者都是一樣的。 – user2618875

+1

** @ GoNeale,**而不是傳遞uri,如果我直接傳遞url,響應是一樣的。不過,我會嘗試你的代碼片段。 – user2618875