无法转换为' string'到' System.Net.Http.HttpRequestMessage'

时间:2017-07-24 18:02:59

标签: c# asp.net .net xamarin xamarin.android

我对c#非常陌生并且一般会发出API请求,所以不确定我的代码是否有意义。我现在只是尝试从API的网址调用中获取数据并将其显示在名为TextView的{​​{1}}上。无论我能开展工作,我都可以使用testTextRestSharp

HttpClient

在我的公开public class MainActivity : Activity { HttpClient client; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); } public async Task<string> GetResponseString() { var request = "http://localhost:51843/api/values/getMessage?id=1"; var response = await client.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); return content; } } 方法中,我正在获取

  

无法转换为&#39; string&#39;到&#39; System.Net.Http.HttpRequestMessage&#39;

async Task<>变量的

错误。我留下了我所有其他尝试的评论,让我知道我是否应该尝试其中任何一个

2 个答案:

答案 0 :(得分:4)

SendAsync有一个参数HttpRequestMessage,你传递一个字符串。这正是错误告诉你的。

如果查找HttpRequestMessage,则需要方法和URI

var url = "http://localhost:51843/api/values/getMessage?id=1";
var req = new HttpRequestMessage(HttpMethod.POST, new Uri(url));

答案 1 :(得分:2)

您还可以使用HttpClient.GetAsyncHttpClient.PostAsync,具体取决于所请求的性质。这些方法确实有重载string URI。

例如

HttpClient client = new HttpClient();
public async Task<string> GetResponseString() {
    var request = "http://localhost:51843/api/values/getMessage?id=1";
    var response = await client.GetAsync(request);
    var content = await response.Content.ReadAsStringAsync();
    return content;
}

这是同一方法的同步版本

HttpClient client = new HttpClient();
public string GetResponseString() {
    var request = "http://localhost:51843/api/values/getMessage?id=1";
    var response = client.GetAsync(request).Result;
    var content = response.Content.ReadAsStringAsync().Result;
    return content;
}