优化下面得到代码,internal async Task<ResponseResult> PostDataAsync(string url, String param) { //await new MessageDialog(param, "parsm").ShowAsync(); Uri requestUri = new Uri(BaseLocalHost + $"{url}"); ResponseResult httpResponseBody = new ResponseResult(); string res = ""; HttpStringContent content = new HttpStringContent( param, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json" ); try { HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(requestUri, content); // await new MessageDialog(httpResponseMessage.StatusCode.ToString(), "响应状态").ShowAsync(); httpResponseMessage.EnsureSuccessStatusCode(); var res1 = await httpResponseMessage.Content.ReadAsStringAsync(); //res1 typeof string 我想要得到的是ResponseResult类型 //httpResponseBody = res1; #region 数据格式转换 var serializer = new DataContractJsonSerializer(typeof(ResponseResult)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(res1)); httpResponseBody = serializer.ReadObject(ms) as ResponseResult; #endregion await new MessageDialog(httpResponseBody.message.ToString(),"响应体").ShowAsync(); return httpResponseBody; } catch (Exception ex) { res = "Error:" + ex.HResult.ToString("X") + "Message:" + ex.Message; await new MessageDialog(res, "网络请求失败").ShowAsync(); return httpResponseBody; } }
时间: 2024-02-14 14:24:59 浏览: 73
下面是对你提供的代码进行优化的建议:
```csharp
internal async Task<ResponseResult> PostDataAsync(string url, string param)
{
Uri requestUri = new Uri(BaseLocalHost + url);
ResponseResult httpResponseBody = new ResponseResult();
try
{
HttpStringContent content = new HttpStringContent(param, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(requestUri, content);
httpResponseMessage.EnsureSuccessStatusCode();
string res1 = await httpResponseMessage.Content.ReadAsStringAsync();
httpResponseBody = ConvertToResponseResult(res1);
await new MessageDialog(httpResponseBody.message.ToString(), "响应体").ShowAsync();
return httpResponseBody;
}
catch (Exception ex)
{
string res = "Error:" + ex.HResult.ToString("X") + "Message:" + ex.Message;
await new MessageDialog(res, "网络请求失败").ShowAsync();
return httpResponseBody;
}
}
private ResponseResult ConvertToResponseResult(string json)
{
var serializer = new DataContractJsonSerializer(typeof(ResponseResult));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return serializer.ReadObject(ms) as ResponseResult;
}
}
```
优化说明:
1. 将参数类型由 `String` 改为 `string`,与 C# 的命名约定一致。
2. 将参数的初始化放在使用之前,避免不必要的初始化。
3. 将数据格式转换的代码抽取到一个单独的方法 `ConvertToResponseResult` 中,提高代码的可读性和复用性。
4. 使用 `using` 语句来确保资源的正确释放。
希望以上优化建议对你有帮助!如果你还有其他问题,请随时提问。
阅读全文