WebClient.OpenReadAsync - 如何发布变量而不是使用查询字符串

时间:2012-06-29 08:17:23

标签: windows-phone-7 post webclient

我正在使用以下代码从我的网络服务器中检索json字符串:

var webClient = new WebClient();

webClient.OpenReadCompleted += OnOpenReadCompleted;

webClient.OpenReadAsync(new Uri("https://myurl.com/request.cgi?user=" + user + "&pass=" + pass + "&junk=" + DateTime.Now, UriKind.Absolute));

...

private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// response processed here
}

我打算对所使用的变量进行加密,但希望能够将变量发布到服务器,而不是将它们包含在查询字符串中。我怎么做到这一点?

谢谢 - Stu

编辑:已将代码更改为以下内容:

var webClient = new WebClient();

                    webClient.UploadStringCompleted += OnOpenReadCompleted;
                    webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
                    webClient.Encoding = Encoding.UTF8;


                  webClient.UploadStringAsync(new Uri("https://myurl.com/request.cgi"), "POST", "user=" + user + "&pass=" + pass + "&junk=" + DateTime.Now, UriKind.Absolute); 

...

private void OnOpenReadCompleted(object sender, UploadStringCompletedEventArgs e)
    {
    // response processed here
    }

作为响应处理的一部分,我检查了Isolatedstorage中是否存了已保存的文件,如果存在,则将其删除并将新响应保存到文件中。

但是,由于现在将代码更改为高于它,我不会删除现有文件:

private void OnOpenReadCompleted(object sender, UploadStringCompletedEventArgs e)
    {
        StreamReader reader = new StreamReader(e.Result);
        string myresult = reader.ReadToEnd();
        reader.Close();
        reader.Dispose();
        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
                if (store.FileExists("json.txt")) 
                    { 
                       store.DeleteFile("json.txt");   // this errors with System.MethodAccessException was unhandled
        //  Message=Attempt to access the method failed: System.IO.StreamReader..ctor(System.String)
                    }
         ...
     } 

不明白为什么代码更改会影响这个?

编辑:

通过更改修复:

StreamReader reader = new StreamReader(e.Result);
string myresult = reader.ReadToEnd();
reader.Close();
reader.Dispose();

string myresult = (string)e.Result;

1 个答案:

答案 0 :(得分:1)

使用上传字符串发布数据:webClient.UploadStringAsync(uri,“POST”,body); 您只需要配置服务器想要查看它的“正文”数据。

相关问题