我的代码如下:
public static void sendData()
{
try
{
WebClient wc = new WebClient();
var URI = new Uri("abc.com");
string str = "data=1234";
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc__UploadStringCompleted);
wc.UploadStringAsync(URI, "POST", str);
}
catch (Exception ex)
{
string temp = ex.Message;
}
}
public static void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
string tt = e.Result;
}
catch (Exception exc)
{
}
}
它是发送sucessfull到服务器,但它不能收集数据响应。请告诉我如何响应数据,我想在sendData方法得到响应不委托和wc__UploadStringCompleted不调用
答案 0 :(得分:1)
public static async Task<string> sendData()
{
TaskCompletionSource<string> complete = new TaskCompletionSource<string>();
try
{
WebClient wc = new WebClient();
var URI = new Uri("abc.com");
string str = "data=1234";
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.UploadStringCompleted += (s, e) =>
{
try
{
string tt = e.Result;
complete.SetResult(tttt);
}
catch (Exception exc)
{
complete.SetException(exc);
}
}
wc.UploadStringAsync(URI, "POST", str);
}
catch (Exception ex)
{
string temp = ex.Message;
complete.SetException(ex);
}
return await complete.Task;
}
用法:
public async void foo()
{
string response = await sendData();
}
答案 1 :(得分:0)
如果您的意思是,您希望在sendData()
方法中进行响应,则可以在sendData()
本身中连接处理程序。
wc.UploadStringCompleted += (s,e)=>
{
try
{
string tt = e.Result;
}
catch (Exception exc)
{
}
}