Xamarin原生共享项目HttpClient不起作用

问题描述:

我创建了支持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 }; 
     } 
    } 

调试通过,并暂停在线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