1

我想在 C# 中编写一个类,它应该将 HTTP 请求(发布)发送到我服务器上的 PHP 文件,以便检索 json 对象。

这是我得到的代码:

   public void SendRequest(){
    HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create("url");

    // execute the request
    HttpWebResponse response = (HttpWebResponse)
        request.GetResponse();
    }

那是我需要的吗?你认为我应该改变或改进什么?谢谢您的帮助。

4

1 回答 1

1

您需要发布数据并阅读响应:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
string yourPostData = "Your post data";
string sreverResponseText;

byte[] postDataBytes = Encoding.UTF8.GetBytes(yourPostData);
request.ContentLength = yourPostData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";

using (Stream requestStream = request.GetRequestStream())
      requestStream.Write(postDataBytes, 0, postDataBytes.Length);

using (response = (HttpWebResponse)request.GetResponse())
      using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            sreverResponseText = streamReader.ReadToEnd();

现在您要查找的内容在 中sreverResponseText,您也可以从response.Headers.ToString()

于 2013-04-19T23:21:47.830 回答