First of all, I wrote a simple php page, that picks up some variables from the POST parameters such as a query and a authentication string, and returns the result as xml. I intend to call this page with the WebClient class from a Silverlight 开发者_如何学JAVAapplication. I'm using POST because we are querying the database with any valid sql statement, not only select statements. The WebClient class uses the UploadDataAsync method to post to a http server, however it requires the post parameters be passed as a NameValueCollection. This class is missing in the Silverlight runtime. How do I proceed???
Use the WebRequest API instead of the WebClient API.
var request = WebRequest.Create(requestUriString);
request.Method = "POST";
request.BeginGetRequestStream()
WebClient webClient = new WebClient();
webClient.Headers["content-type"] = "application/x-www-form-urlencoded";
webClient.Encoding = Encoding.UTF8;
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
webClient.UploadStringAsync(new Uri(courseListUrl, UriKind.Absolute), "POST", apend);
Where apend
is your string, that you send over POST-Method
after it UploadCompleteMethod:
void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
string k = e.Result;
}
If you want to use Cookies inside of the WebClient, you can also do it, but you have to create a Descendant class from WebClient, like this:
public class CookieAwareWebClient : WebClient
{
private CookieContainer m_container = new CookieContainer();
[System.Security.SecuritySafeCritical]
public CookieAwareWebClient() : base() { }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}
after it you just change WebClient webClient = new WebClient();
to CookieAwareWebClient webClient = new CookieAwareWebClient();
精彩评论