我正在构建我的第一个
windowsPhone 8.1应用程序,我的应用程序的作用是创建与服务器的连接以从中获取信息,所以我编写代码来执行此过程通过向服务器发送json-rpc请求来获取一些信息,我我是第一次成功获得它但是当我发送第二个请求时,我收到一个404错误的空响应(找不到页面).
但是当我在没有https(仅限http)的情况下调用该服务时,无论我多少次调用它,它都能正常工作!
但是当我在没有https(仅限http)的情况下调用该服务时,无论我多少次调用它,它都能正常工作!
public async Task<string> GetDataFromServer(string urlToCall,string JSONData,string RR) { string UserName = “XXXXXXX” string Password = "XXX"; using ( var handler = new HttpClientHandler()) { handler.Credentials = new NetworkCredential(UserName,Password); HttpClient client = new HttpClient(handler); HttpResponseMessage response = null; try { response = await client.PostAsync(urlToCall,new StringContent(JSONData.ToString(),Encoding.UTF8," application/json")); string res = response.Content.ReadAsStringAsync().Result; Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog(res); await g.ShowAsync(); return res; } catch (Exception ex) { Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog("Error is : " + ex.Message); g.ShowAsync(); return "Error"; } finally { response.Dispose(); client.CancelPendingRequests(); client.Dispose(); handler.Dispose(); } } }
再次,当第一次调用服务的URL(以https开头)时我得到了搜索数据的响应,但第二次收到404错误的空响应(找不到页面)!!
请帮忙
解决方法
请尝试使用此解决方案.
public async Task<string> SendJSONData3(string urlToCall,string JSONData) { string UserName = "XXXXXXXXX"; string Password = "XXXXXXXXX"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlToCall); httpWebRequest.Credentials = new NetworkCredential(UserName,Password); httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) { string json = JSONData; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; } }