3

我正在尝试将发布数据(json)发送到网络服务器。这是非常基本的东西,但在 Windows 8 api 中,一切都必须很复杂:/ Microsoft 提供的示例根本不起作用http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664/sourcecode?fileId=50955&pathId =797575364 scenerio 5 - 它正在向服务器发送一些东西,但没有应该发送的东西(也许当我将字符串转换为流时有一些问题......)

            byte[] byteArray = Encoding.Unicode.GetBytes( data );
            MemoryStream stream = new MemoryStream( byteArray );
            StreamContent streamContent = new StreamContent(stream);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
            request.Content = streamContent;
            request.Headers.TransferEncodingChunked = true; 
            var httpClient = new HttpClient();

            HttpResponseMessage response = await httpClient.SendAsync(request);

            string responseString = await response.Content.ReadAsStringAsync();

但我想出了另一个想法,这个解决方案有效(但是......)

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";

            using (var requestStream = await request.GetRequestStreamAsync())
            {
                var writer = new StreamWriter(requestStream);
                writer.Write(data);
                writer.Flush();
            }

            using (var response = await request.GetResponseAsync()) 
            {
                using (var responseStream = response.GetResponseStream())
                {
                    var reader = new StreamReader(responseStream);
                    var answer = reader.ReadToEnd();
                    return answer;
                }
            }

正如我之前所说,这种解决方案有很大的缺点——服务器响应可能有 http 代码 422,然后应用程序立即崩溃。如何使用第二种解决方案检查 http 响应代码?(我不确定这是否可能,因为它会崩溃request.GetResponseAsync

提前致谢 :)

4

1 回答 1

0

用 try-catch 块包装代码的主体并处理WebException错误调用。WebException.Status包含请求失败原因的状态代码。

var request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "POST";
try {
// Your code
}
 catch (WebException)
{ //error handling
}
于 2012-08-30T22:03:32.467 回答