使用C#构建url字符串

时间:2013-08-26 20:17:30

标签: c# json

我一直在尝试为我的json请求构建请求URL,但是遇到了404错误。这是我在阅读了一些线程后放在一起的代码。有人可以帮忙吗?

var apiKey = "123456";
var Query = "some search";
var Location = "San Jose, CA";
var Sort = "1";
var SearchRadius = "100";

var values = HttpUtility.ParseQueryString(string.Empty);

values["k"] = apiKey;
values["q"] = Query;
values["l"] = Location;
values["sort"] = Sort;
values["radius"] = SearchRadius;

string url = "http://api.website.com/api" + values.toString();

这是我收到错误的地方。在client.DownloadString()

上传递url之后
var client = new WebClient();
var json = client.DownloadString(url);
var search = Json.Decode(json);

2 个答案:

答案 0 :(得分:2)

您的代码正在构建无效的网址:

http://api.website.com/apik=123456&q=some+search&l=San+Jose%2c+CA&sort=1&radius=100

请注意/apik=123456部分。

var apiKey = "123456";
var Query = "some search";
var Location = "San Jose, CA";
var Sort = "1";
var SearchRadius = "100";

// Build a List of the querystring parameters (this could optionally also have a .ToLookup(qs => qs.key, qs => qs.value) call)
var querystringParams = new [] {
  new { key = "k", value = apiKey },
  new { key = "q", value = Query },
  new { key = "l", value = Location },
  new { key="sort", value = Sort },
  new { key = "radius", value = SearchRadius }
};

// format each querystring parameter, and ensure its value is encoded
var encodedQueryStringParams = querystringParams.Select (p => string.Format("{0}={1}", p.key, HttpUtility.UrlEncode(p.value)));

// Construct a strongly-typed Uri, with the querystring parameters appended
var url = new UriBuilder("http://api.website.com/api");
url.Query = string.Join("&", encodedQueryStringParams);

此方法将使用UrlEncoded查询字符串参数构建有效的强类型Uri实例。如果您需要在多个位置使用它,可以很容易地将其转换为辅助方法。

答案 1 :(得分:0)

使用UriBuilder class。它将确保生成的URI格式正确。