-1

我一直在尝试为我的 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);
4

2 回答 2

2

您的代码正在构建一个无效的 URL:

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 实例。如果您需要在多个位置使用它,它可以很容易地转入辅助方法。

于 2013-08-26T20:20:06.647 回答
0

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

于 2013-08-26T20:27:17.493 回答