如何使用Visual C发送帖子请求#

时间:2015-06-07 23:24:27

标签: c# windows visual-studio-2012

我想使用XAML和C#从Windows应用程序创建一个包含网站的身份验证页面。

我尝试使用以下代码:

private void SubmitData()
    {
        try
        {
            string user = textBox1.Text;
            string pass = textBox2.Text;

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "user=" + user + "&pass=" + pass;
            byte[] data = encoding.GetBytes(postData);

            WebRequest request = WebRequest.Create("http://charnycoding.info/WebRequestPOST.php");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            Stream stream = request.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();

            WebResponse response = request.GetResponse();
            stream = response.GetResponseStream();

            StreamReader sr = new StreamReader(stream);
            MessageBox.Show(sr.ReadToEnd());

            sr.Close();
            stream.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error : " + ex.Message);
        }
    }

但是在编译时会显示request.ContentType没有任何定义的错误。

1 个答案:

答案 0 :(得分:0)

你需要做一些研究

http://www.codeproject.com/Articles/275279/Developing-WCF-Restful-Services-with-GET-and-POST

言 在本文中,我们将了解如何创建基于WCF REST的服务。在这个例子中,我们将定义两个方法,GetSampleMethod(方法类型是GET)& PostSampleMethod(方法类型为POST)。

GET方法将输入作为String&返回格式化字符串 POST方法将输入为XML(用户注册)&返回状态字符串。 注意:一个人应该具备什么是WCF的基本知识,为什么WCF&我的文章将讨论如何在WebHttpBinding中使用WCF。

我们将这篇文章分为以下部分:

定义WCF服务 定义接口 定义类 实施POST& GET方法 定义WCF服务的配置 服务配置 行为配置 Smoke测试WCF服务(在客户端使用之前) 实现客户端代码以使用WCF服务 定义WCF服务 打开VS 2010&选择新项目,然后选择WCF&选择WCF服务应用程序&将其命名为WCF Rest Based。 现在将新的Service类添加到此应用程序中作为“MyService.svc” 开放接口IMservice.cs&添加以下代码: OperationContract:PostSampleMethod WebInvoke方法Type = POST,因为我们正在实施POST URI模板定义用于标识/链接此方法的URL格式。 注意:MethodName,URI模板名称&操作合同名称可能不同意味着它们可能不同 PostSampleMethod将接受XML字符串作为POST方法的输入。使用Stream作为输入参数,我们可以在使用之前对输入数据进行反序列化。 隐藏复制代码

[OperationContract(Name = “PostSampleMethod”)]
    [WebInvoke(Method = “POST”,
     UriTemplate = “PostSampleMethod/New”)]
    string PostSampleMethod(Stream data);
OperationContract name: GetSampleMethod
WebGet attribute defined method type is GET
Need to include below namespaces:
Hide   Copy Code
System.ServiceModel.Web;
System.ServiceModel
System.Runtime.Serialization
System.IO
[OperationContract(Name = “GetSampleMethod”)]
    [WebGet(UriTemplate = “GetSampleMethod/inputStr/{name}”)]
    string GetSampleMethod(string name);

打开MyService.cs类并为IMyService Interface中定义的方法提供实现,如下所示:

隐藏复制代码

public string PostSampleMethod(Stream data)
 {
    // convert Stream Data to StreamReader
    StreamReader reader = new StreamReader(data);
    // Read StreamReader data as string
    string xmlString = reader.ReadToEnd();
    string returnValue = xmlString;
    // return the XMLString data
    return returnValue;
    }
    public string GetSampleMethod(string strUserName)
{
    StringBuilder strReturnValue = new StringBuilder();
    // return username prefixed as shown below
    strReturnValue.Append(string.Format
    (”You have entered userName as {0}”, strUserName));
    return strReturnValue.ToString();
    }

定义WCF服务的配置 打开web.config,因为我们需要为WCF服务定义配置。如果您希望我们的服务作为webHttp的一部分进行访问,那么我们需要定义webHttpBinding& mexHttpBinding。 在System.ServiceModel中定义的配置如下所示。要了解有关以下配置配置的详细信息,请查看URL:https://ch1blogs.cognizant.com/blogs/279850/2011/10/18/service-end-point-not-found/。 隐藏复制代码

<services>
  <service name=”WcfRestBased.MyService” 
behaviorConfiguration=”myServiceBehavior” >
    <endpoint name=”webHttpBinding”
              address=”"
              binding=”webHttpBinding”
              contract=”WcfRestBased.IMyService”
              behaviorConfiguration=”webHttp”
              >
            </endpoint>
    <endpoint name=”mexHttpBinding”
              address=”mex”
              binding=”mexHttpBinding”
              contract=”IMetadataExchange”
              />
  </service>
</services>

服务名称:要查找要给出的内容,请右键单击服务&amp;选择ViewMarkup选项。

示例,在我的例子中,它是MyService.svc,查找Service属性&amp;使用完整的字符串,在我的例子中是Service =“WcfRestBased.MyService”。

behaviorConfiguration:可以是任何名称,但在我们定义行为设置时会再次使用它,在我的例子中它是myServiceBehavior。

webHttpBinding的端点

端点名称:如果要配置Web访问,则应为webHttpBinding 地址:我们可以把它留空 绑定:应该是webHttpBinding contract:应该是Namespace.Interfacename。在我的例子中,它是wcfRestBased.IMyService behaviorConfiguration:应该是webHttp EndPoint for mexHttpBinding

这些值应与上面显示的相同。

现在定义Service行为,如下所示在System.ServiceModel中。 “mySeriveBehavior”名称应与Service tag中定义的behaviorConfiguration名称匹配(如上所示): 隐藏复制代码

<behaviors>
  <serviceBehaviors>
    <behavior name=”myServiceBehavior” >
      <serviceMetadata httpGetEnabled=”true”/>
      <serviceDebug includeExceptionDetailInFaults=”false” />
    </behavior>
    <behavior>
      <!– To avoid disclosing metadata information, 
    set the value below to false and remove the metadata endpoint 
    above before deployment –>
      <serviceMetadata httpGetEnabled=”true”/>
      <!– To receive exception details in faults for debugging purposes, 
    set the value below to true. Set to false before deployment 
    to avoid disclosing exception information –>
      <serviceDebug includeExceptionDetailInFaults=”false”/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name=”webHttp”>
      <webHttp/>
    </behavior>
  </endpointBehaviors>
    </behaviors>

Smoke Test WCF服务 在IIS中配置WCF服务 要检查我们的WCF服务是否正常工作,让我们通过在浏览器中打开MyService.svc来测试它,在我的例子中它是http://localhost/wcfrestbased/MyService.svc 要测试我们的GET方法服务,您可以通过http://localhost/wcfrestbased/MyService.svc/GetSampleMethod/inputStr/suryaprakash&amp;这会将数据显示为“您已输入userName as suryaprakash”。 通过这个,我们可以确认我们的服务工作正常。 实现客户端代码以使用WCF服务 创建新的网站应用程序,作为客户端访问WCF服务。 将文本框添加到default.aspx页面&amp;将其命名为txtResult&amp;打开Default.aspx.cs 定义下面的函数,它将调用rest服务来获取数据。此方法将调用服务中的POSTSAMPLEMETHOD(MyService)实现。内联代码注释已添加。 隐藏缩小复制代码

void CallPostMethod()
    {
        // Restful service URL
        string url = 
     “http://localhost/wcfrestbased/myservice.svc/PostSampleMethod/New“;

        // declare ascii encoding
        ASCIIEncoding encoding = new ASCIIEncoding();
        string strResult = string.Empty;
        // sample xml sent to Service & this data is sent in POST
        string SampleXml = @”<parent>” +
                “<child>” +
                    “<username>username</username>” +
                    “<password>password</password>” +
                “</child>” +
              “</parent>”;
        string postData = SampleXml.ToString();
        // convert xmlstring to byte using ascii encoding
        byte[] data = encoding.GetBytes(postData);
        // declare httpwebrequet wrt url defined above
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        // set method as post
        webrequest.Method = “POST”;
        // set content type
        webrequest.ContentType = “application/x-www-form-urlencoded”;
        // set content length
        webrequest.ContentLength = data.Length;
        // get stream data out of webrequest object
        Stream newStream = webrequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        // declare & read response from service
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

        // set utf8 encoding
        Encoding enc = System.Text.Encoding.GetEncoding(”utf-8?);
        // read response stream from response object
        StreamReader loResponseStream = 
    new StreamReader(webresponse.GetResponseStream(), enc);
        // read string from stream data
        strResult = loResponseStream.ReadToEnd();
        // close the stream object
        loResponseStream.Close();
        // close the response object
        webresponse.Close();
        // below steps remove unwanted data from response string
        strResult = strResult.Replace(”</string>”, “”);
            strResult = strResult.Substring(strResult.LastIndexOf(’>

现在让我们继续并实现从客户端应用程序调用GETSAMPLEMETHOD的代码。以下代码具有内联注释: 隐藏复制代码

void CallGetMethod()
    {
        // Restful service URL
        string url = “http://localhost/wcfrestbased/myservice.svc/
        GetSampleMethod/inputStr/suryaprakash“;
        string strResult = string.Empty;
        // declare httpwebrequet wrt url defined above
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        // set method as post
        webrequest.Method = “GET”;
        // set content type
        webrequest.ContentType = “application/x-www-form-urlencoded”;
        // declare & read response from service
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
        // set utf8 encoding
        Encoding enc = System.Text.Encoding.GetEncoding(”utf-8?);
        // read response stream from response object
        StreamReader loResponseStream = new StreamReader
            (webresponse.GetResponseStream(), enc);
        // read string from stream data
        strResult = loResponseStream.ReadToEnd();
        // close the stream object
        loResponseStream.Close();
        // close the response object
        webresponse.Close();
        // assign the final result to text box
       txtResult.Text = strResult;
        }

现在继续调用上面的方法来查看每个方法的输出。