在Windows 8上发送发布数据

时间:2012-08-30 21:48:48

标签: c# windows-8

我正在尝试将帖子数据(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

上崩溃了

提前致谢:)

1 个答案:

答案 0 :(得分:0)

使用try-catch块包裹代码的主体,并在错误的调用中处理WebExceptionWebException.Status包含请求失败原因的状态代码。

var request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "POST";
try {
// Your code
}
 catch (WebException)
{ //error handling
}