GetRequestStream()超时异常

时间:2018-09-21 06:49:30

标签: c# android xamarin.android httprequest webclient

我想使用Webclient发出一个简单的Http请求:

public string PostRequest(object json, string contentType, string server)
{
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(server);
        request.ContentType = contentType;
        request.Method = "POST";
        request.Timeout = 10000;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(JsonConvert.SerializeObject(json));
        }


        var response = (HttpWebResponse)request.GetResponse();
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            return streamReader.ReadToEnd();
        }
    }
    catch (Exception e)
    {
        throw e;
    }

}

问题在于request.GetRequestStream()部分从不返回,并且总是超时(默认值为100和10)。我在Android 7和更高版本的Android 8.1上使用了三星xcover 4。将服务器字符串复制到PC上的标准浏览器后,它可以完美工作。在设备浏览器本身上,它不起作用(超时)。 contentType是“ application / json”。

是否可以解决此问题,或者是否有其他方法可以在xamarin中发送未损坏的httprequest?

服务器本身正在运行,我可以通过设备ping它:

public int PingHost(string nameOrAddress)
{
    int pingCount = 0;
    Ping pinger = null;
    for (int i = 0; i < 4; i++)
    {
        try
        {
            pinger = new Ping();
            PingReply reply = pinger.Send(nameOrAddress);
            pingCount += reply.Status == IPStatus.Success ? 1:0;
        }
        catch (Exception){ pingCount = - 1; }
        finally
        {
            pinger?.Dispose();
        }
        if (pingCount == -1) return -1;

    }
    return pingCount;
}

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

我的应用程序中有一个工作代码,它是这样的:

 public HttpClient apiClient;

GetType API

 public async Task<string> GetServiceData(string srvUrl)
    {
        try
        {
          apiClient = new HttpClient(new NativeMessageHandler(throwOnCaptiveNetwork: false, customSSLVerification: false)); // SSL true if you have custom SLL in your API 
          apiClient.BaseAddress = new Uri(_yourbaseUrl); // Url where the service is hosted
          apiClient.DefaultRequestHeaders.Add("",""); //defualt req header key value in case any
          var respon = await apiClient.GetAsync(srvUrl).Result.Content.ReadAsStringAsync(); // svrUrl is the name of the api that you want to consume 
          if (respon != string.Empty)
          {
               return respon;
          }
        }
        catch (HttpRequestException reqEx)
        {
           return string.Empty;
        }
        catch (Exception ex)
        {
           return string.Empty;
        }
    }

PostType API

  public async Task<string> PostServiceData(string srvUrl, object srvModel)
    {
        try
        {
          var myContent = JsonConvert.SerializeObject(srvModel);//your parameter to the API
          var stringContent = new StringContent(myContent, Encoding.UTF8, "application/json");
          apiClient = new HttpClient(new NativeMessageHandler(throwOnCaptiveNetwork: false, customSSLVerification: true));// SSL true if you have custom SLL in your API
          apiClient.BaseAddress = new Uri(_yourbaseUrl); // Url where the service is hosted
          apiClient.DefaultRequestHeaders.Add("",""); //defualt req header key value in case any
          apiClient.DefaultRequestHeaders.Accept
               .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
            var respon = await apiClient.PostAsync(srvUrl, stringContent);
                var resReslt = respon.Content.ReadAsStringAsync().Result;
                return resReslt;
            }
            else
                return string.Empty;

        }
        catch (HttpRequestException reqEx)
        {
            return string.Empty;
        }
        catch (Exception ex)
        {
            return string.Empty;
        }

祝您好运,以防查询退回!

相关问题