通过HttpClient的HTTP Post的UrlEncode非字符串属性 [英] UrlEncode non-string properties for HTTP Post through HttpClient

查看:812
本文介绍了通过HttpClient的HTTP Post的UrlEncode非字符串属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在python中

This code is in python

dataParams = urllib.urlencode({
    "name": "myname",      
    "id": 2,        
    })

    dataReq = urllib2.Request('mylink', dataParams)
    dataRes = urllib2.urlopen(dataReq)

现在我正在尝试将其转换为C#.到目前为止,我只能执行此操作

Now i am trying to convert it into C#.Till now I have been able to do this only

 var dataParams = new FormUrlEncodedContent(
             new KeyValuePair<string, string>[]
             {
                 new KeyValuePair<string, string>("name", myname"),                     
                 new KeyValuePair<string, string>("id", "2"),
             });

  httpResponse = await httpClient.PostAsync(new Uri(dataString),dataParams);
  httpResponseBody = await httpResponse.Content.ReadAsStringAsync();   

但是我的问题是发布内容,因为发布数据需要同时为int和string.但是我只能使用FormUrlEncodedContent以字符串格式发送数据.因此,如何发送带有适当参数的发布请求.

But my problem is posting the content since the post data needs to be both int and string.But I am able to only send data in string format using FormUrlEncodedContent.So how do I send the post request with proper parameters.

推荐答案

我不确定post data needs to be both int and string是什么意思,因为

I am not sure what do you mean by post data needs to be both int and string, because application/x-www-form-urlencoded is basically a string with string key-value pairs.

因此,原始id参数是字符串"2"还是数字2都没关系.

So it doesn't matter if your original id parameter is a string "2" or a number 2.

它将被编码为相同的:name=mynameValue&id=2

It will be encoded the same: name=mynameValue&id=2

因此,您的代码没有错.只需对原始int值使用ToString方法即可获取其字符串表示形式:

So there is nothing wrong with your code. Just use ToString method on original int value to get its string representation:

var id = 2;
var dataParams = new FormUrlEncodedContent(
     new KeyValuePair<string, string>[]
     {
         new KeyValuePair<string, string>("name", myname"),                     
         new KeyValuePair<string, string>("id", id.ToString()),
     });


您可以使用类似的方法以更少的样板来编码复杂类型,甚至看起来更像原始的python代码:


You can make something like this to urlencode complex types with less boilerplate, and it will even look more like the original python code:

public static class HttpUrlEncode
{
    public static FormUrlEncodedContent Encode(Object obj)
    {
        if (obj == null)
            throw new ArgumentNullException("obj");

        var props = obj
            .GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .ToDictionary(
                prop => 
                    prop.Name,
                prop => 
                    (prop.GetValue(obj, null) ?? String.Empty).ToString());

        return new FormUrlEncodedContent(props);
    }
}


var dataParams = HttpUrlEncode.Encode(
    new 
    {
        name = "myname",
        id = 2
    });       

这篇关于通过HttpClient的HTTP Post的UrlEncode非字符串属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆