此代码在python中。
dataParams = urllib.urlencode({
"name": "myname",
"id": 2,
})
dataReq = urllib2.Request('mylink', dataParams)
dataRes = urllib2.urlopen(dataReq)现在我正试图把它转换成C#.Till,现在我只能这样做了
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(); 但是我的问题是发布内容,因为post数据需要是int和string.But,我只能使用FormUrlEncodedContent.So以字符串格式发送数据,如何使用适当的参数发送post请求。
发布于 2017-01-12 18:35:20
我不知道post data needs to be both int and string是什么意思,因为应用程序/x-www-表单-urlencoded基本上是一个具有字符串键值对的字符串。
因此,您的原始id参数是字符串"2"还是数字2并不重要。
它将被编码相同:name=mynameValue&id=2
所以你的代码没有什么问题。只需对原始的ToString值使用int方法来获得其字符串表示形式:
var id = 2;
var dataParams = new FormUrlEncodedContent(
new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("name", myname"),
new KeyValuePair<string, string>("id", id.ToString()),
});您可以使用较少的样板将类似的内容用于urlencode复杂类型,它甚至看起来更像最初的python代码:
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
}); 发布于 2017-01-13 03:17:15
如果您不介意一个小库依赖项,弗勒尔公开:我是作者,它和您的Python示例一样简短和简洁,也许更简单:
var dataParams = new {
name: "myname",
id: 2
};
var result = await "http://api.com".PostUrlEncodedAsync(dataParams).ReceiveString();发布于 2017-01-12 18:23:39
如果数据同时包含数字和字符串值,则可以使用KeyValuePair<string,object>,它应该可以接受任何数据。所以你的代码可能是:
var contentString = JsonConvert.SerializeObject(
new KeyValuePair<string, object>[]
{
new KeyValuePair<string, object>("name", "myname"),
new KeyValuePair<string, object>("id", 2),
});
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "URI") {
Content = new StringContent(contentString)
};
httpResponse = await httpClient.SendAsync(requestMessage);https://stackoverflow.com/questions/41620252
复制相似问题