Httpclient Post Webapi
格式:
application/x-www-form-urlencoded 提交的数据按照 key1=val1&key2=val2 的方式进行编码
multipart/form-data 必须让 表单的 enctype 等于 multipart/form-data,可以传键值对,也可以上传文件
原生 表单也只支持这两种方式(通过 元素的 enctype 属性指定,默认为 application/x-www-form-urlencoded)
application/json json一般是接收格式,也可以作为提交格式,使用StringContent方法,服务器端需要对应处理,一般应对格式复杂数据
参数:
.net 提交参数以KeyValuePair 集合形式,可以使用Dictionary,使用FormUrlEncodedContent方法创建httpcontent
private void btn_post_Click(object sender, EventArgs e)
{
string url = @"http://api.apishop.net/common/joke/getJokesByRandom";
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "apiKey", "***********" },
{ "pageSize", "3" }
};
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
//string json = JsonConvert.SerializeObject(new {
// apiKey = "",
// pageSize = "3"
//});
//var content = new StringContent(json, Encoding.UTF8, "application/json");
//HttpResponseMessage response = client.PostAsync(url, content).Result;
//string responseBody = response.Content.ReadAsStringAsync().Result;
}