Simple requirement . I have a class - User - {userId, userName, age}.
How to serailize a object of the class and sent to a url (using post) using webclient.
Something Like below.
What is the best开发者_如何学运维 way to serialise user object into postdata format.
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
string postData = "orderId=5&status=processed2&advertId=ADV0001a";
byte[] postArray = Encoding.ASCII.GetBytes(postData);
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
byte[] responseArray = client.UploadData(address, postArray);
var result = Encoding.ASCII.GetString(responseArray);
return result;
I would apply the following simplification to your code:
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
var data = new NameValueCollection
{
{ "userId", user.Id },
{ "userName", user.Name },
{ "age", user.Age }
};
var responseArray = client.UploadValues(address, data);
return Encoding.ASCII.GetString(responseArray);
}
精彩评论