我想获得一个在c#中使用以下配置生成http帖子的方法。
POST pqs.php HTTP/1.1
Host: nationalmap.gov/epqs/pqs.php
Content-Type: application/x-www-form-urlencoded
Content-Length: length
x=string&y=string&units=string&output=string
我尝试了以下但是我得到了无效的坐标,尽管它们确实存在于地图中(尝试的例子是lat = 36.574832和lon = -85.411825
以下是我正在使用的代码:
public class ElevationUSGISPull
{
public string responseString = null;
private string BASEURL = "http://nationalmap.gov/epqs/pqs.php";
public bool httpPostElevationRequest( string lon,string lat)
{
try
{
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues(BASEURL, new NameValueCollection()
{
{ "x", lon },
{ "y", lat },
{"units", "feet" },
{"output","json" },
});
string result = System.Text.Encoding.UTF8.GetString(response);
responseString = result;
}
return true;
}
catch(Exception eX)
{
return false;
}
}
}
我得到的错误如下:
<error>General failure: Invalid Coordinates</error>
此外,有人试过.gov网站获取高程数据。我使用谷歌服务器,但它有许多与请求数量相关的限制,我正在尝试为给定区域做很多请求。
下面是一个用于通过良好的json响应来验证纬度和长度的网站。
谢谢大家。
我在这里也尝试过以下示例: http://ronaldrosiernet.azurewebsites.net/Blog/2013/12/07/posting_urlencoded_key_values_with_httpclient
但是给了我以下错误。
Exception thrown: 'System.NullReferenceException'
我将代码修改为:
public async Task<string> HTTPPOST(string lon, string lat)
{
var client = new HttpClient();
client.BaseAddress = new Uri(BASEURL);
var request = new HttpRequestMessage(HttpMethod.Post, "");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("x", lon));
keyValues.Add(new KeyValuePair<string, string>("y", lat));
keyValues.Add(new KeyValuePair<string, string>("units", "feet"));
keyValues.Add(new KeyValuePair<string, string>("output", "json"));
request.Content = new FormUrlEncodedContent(keyValues);
var response = await client.SendAsync(request);
return response.ToString();
}
答案 0 :(得分:1)
经过一个小时的调试后,我注意到我把单位作为参数而不是单位:( ......
public string httpPostElevationRequest( string lon,string lat)
{
try
{
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues(BASEURL, new NameValueCollection()
{
{ "x", lon },
{ "y", lat },
{"unit", "feet" },
{"output","json" },
});
string result = System.Text.Encoding.UTF8.GetString(response);
responseString = result;
}
return responseString;
}
catch(Exception eX)
{
return null;
}
}
同样baseurl如下:
private string BASEURL = "https://nationalmap.gov/epqs/pqs.php";
答案 1 :(得分:0)
使用.NET HttpClient 查找示例here