我正在使用简单的本地WCF服务对Xamarin Android应用程序进行一些测试,以证明我的连接代码有效 .
服务:[OperationContract] string Ping(); ... public string Ping(){return“Pong”; }
Xamarin App中的测试代码:
var request = HttpWebRequest.Create(string.Format(@"http://192.168.1.175/_Services/TestService1.svc/Ping"));
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = 0; //pass.Length;
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //Errors out here
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
错误:
远程服务器返回错误:(400)错误请求 .
编辑:
使用ServiceReference时,以下工作:
private void button3_Click(object sender,EventArgs e){ServiceReference1.TestService1Client client = new ServiceReference1.TestService1Client();
string returnString;
returnString = client.Ping();
label1.Text = returnString;
}
稍微不同的代码仍然不起作用:private void button4_Click(object sender,EventArgs e){// string serviceUrl =“_ http://192.168.1.175/_Services/TestService1.svc "; string serviceUrl = " http://localhost/_Services/TestService1.svc”;
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/Ping"));
httpRequest.Accept = "text/xml";
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
httpRequest.KeepAlive = false;
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) //400 Bad Request
{
using (Stream stream = httpResponse.GetResponseStream())
{
label1.Text = (new StreamReader(stream)).ReadToEnd();
}
}
}
1 回答
答案根植于System.ServiceModel.Activation.WebServiceHostFactory
由于某种原因,我的资料在使用HttpWebRequest的研究中没有提到这一点 .
在查看Android WCF消耗时,我偶然发现了这个参考 . https://minafayek.wordpress.com/2013/04/02/consuming-iis-published-restful-wcf-service-from-android-over-wifi/
我让测试程序正常运行,我应该能够继续前进 .