如何更改 WebClient 请求的动词?即使在 DownloadString 的情况下,它似乎也只允许/默认 POST。
try
{
WebClient client = new WebClient();
client.QueryString.Add("apiKey", TRANSCODE_KEY);
client.QueryString.Add("taskId", taskId);
string response = client.DownloadString(TRANSCODE_URI + "task");
result = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(response);
}
catch (Exception ex )
{
result = null;
error = ex.Message + " " + ex.InnerException;
}
提琴手说:
POST http://someservice?apikey=20130701-234126753-X7384&taskId=20130701-234126753-258877330210884 HTTP/1.1
Content-Length: 0
如果您使用 HttpWebRequest,您将获得对调用的更多控制。您可以通过 Method 属性更改 REST 动词(默认为 GET)
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(HostURI);
request.Method = "GET";
String test = String.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
test = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
DeserializeObject(test ...)
不确定是否可以使用 WebClient。但为什么不使用 HttpClient.GetAsync 方法(字符串)http://msdn.microsoft.com/en-us/library/hh158944.aspx
正如在 .NET 源代码中所看到的,DownloadString 的 HTTP 方法取决于私有 WebClient 实例字段 m_Method 的状态,在每次新请求方法调用 (link) 时该字段都会被清除为 null,并且默认为 Web 请求创建者(取决于 URI,例如 ftp 协议获取另一个创建者),但这不是线程安全的。
也许您同时在多个调用之间共享此 WebClient 实例?
所以它变得混乱。这个或 URI 都会让 WebRequest 创建者感到困惑。
所选答案现已过时,这是使用 .NET CORE 的现代示例
namespace GetConsole
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
var url = "https://cat-fact.herokuapp.com/facts/";
ApiResponse apiResponse = getData(url).GetAwaiter().GetResult();
Console.WriteLine(apiResponse.Data);
}
static async Task<ApiResponse> getData(string getEndpoint)
{
ApiResponse apiResponse = new ApiResponse();
using (HttpClient client = new HttpClient())
{
try
{
var response = await client.GetAsync(getEndpoint);
apiResponse.IsSuccess = response.IsSuccessStatusCode;
if (apiResponse.IsSuccess)
{
apiResponse.Data = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
apiResponse.IsSuccess = false;
}
}
return apiResponse;
}
}
}