使用C#调用REST-Api
本文关键字:REST-Api 调用 使用 | 更新日期: 2023-09-27 18:01:09
我使用C#调用Rest API。URL在浏览器中工作,但当我从c#调用它时,一个异常被称为
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
这是我的代码
public static void getInputFromTeam1()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.150.1:8090/api/storeLayout/kinectToRacks/42");
request.Method = "GET";
request.Accept = "application/json";
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
}
}
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
}
我是C#和Rest Api的新手。请帮帮我,我读了很多答案,但没有一个有效。请帮我谢谢你。
我建议您改为查看高级WebClient
-类。您仍然必须密切注意异常消息。
var serviceRequest = new WebClient();
string response = serviceRequest.DownloadString(new Uri(url));
您可以使用此代码。
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://192.168.150.1:8090/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/storeLayout/kinectToRacks/42").Result;
if (response.IsSuccessStatusCode)
{
var str = response.Content.ReadAsStringAsync();
}
}