簡體   English   中英

來自本地WCF服務的HttpWebRequest

[英]HttpWebRequest from a local WCF service

我正在使用簡單的本地WCF服務對Xamarin Android應用進行一些測試,以證明我的連接代碼有效。

服務:[OperationContract]字符串Ping(); …公共字符串Ping(){返回“ 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 ”; 字符串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();
            }
        }
    }

答案植根於System.ServiceModel.Activation.WebServiceHostFactory

由於某種原因,在使用HttpWebRequest的研究過程中,我的任何資料都沒有提到這一點。

在查看Android WCF的使用時,偶然發現了該參考。 https://minafayek.wordpress.com/2013/04/02/using-iis-published-restful-wcf-service-from-android-over-wifi/

我的測試程序正常運行,因此我應該能夠繼續前進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM