开发者

upload serialized data using WebClient

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜