如何在某些特定网址上发布json字符串

时间:2017-02-18 18:48:01

标签: c# json asp.net-mvc asp.net-web-api2

我想使用以下代码在https://api.amplitude.com/httpapi上记录振幅:

private void LogAmplitude()
{
    using (var client = new WebClient())
    {
        var url = "https://api.amplitude.com/httpapi";
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        var model = new { user_Id = "userId", event_type = "Event" };
        var jss = new JavaScriptSerializer();
        var data = jss.Serialize(model);
        string parameters = "api_key=" + "apiKey" + "&event=" + data;
        var response = client.UploadString(url, parameters);
    }
}

但是当我运行这个方法时,它给了我400(错误的请求)错误。我尝试使用邮递员通过以下网址发布数据:

https://api.amplitude.com/httpapi?api_key=apiKey&event={"user_id":"userId","event_type":"test"}

这完全没问题但是当我尝试使用上述方法发布数据时,它总是给我错误。我不确定我做错了什么,因为我第一次做这种工作。那么有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

在文档中说,您可以将GET与urlencoded参数一起使用。

试试这个:

using (var client = new WebClient())
{
    var url = "https://api.amplitude.com/httpapi";
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var model = new { user_id = "userId", event_type = "Event" };
    var jss = new JavaScriptSerializer();
    var data = jss.Serialize(model);
    string parameters = "api_key=" + "apiKey" + "&event=" + System.Uri.EscapeDataString(data);
    var response = client.DownloadString ($"{url}?{parameters}");
}