带有输入类型字段的Web请求

时间:2017-11-19 14:38:13

标签: c# rest httpwebrequest zoho

尝试在这里进行api调用是代码

 public static void Main()
    {
        // Create a request using a URL that can receive a post.   
        WebRequest request = WebRequest.Create("https://creator.zoho.eu/api/programerAnel/xml/testAPP/form/Edit/record/update");
        // Set the Method property of the request to POST.  
        request.Method = "POST";
        // Create POST data and convert it to a byte array.  
        string postData = @"
        < input type=""hidden"" name =""authtoken"" value=""12333"">
        < input type = ""hidden"" name = ""scope"" id = ""scope"" value = ""creatorapi"">
        < input type = ""text"" name = ""criteria"" value = ""UpdateUj=123"" >
        < input type = ""text"" name = ""Kljuc"" value = ""1"" >
        < input type = ""submit"" value = ""Update Record"" > ";

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.  
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.  
        request.ContentLength = byteArray.Length;
        // Get the request stream.  
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.  
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.  
        dataStream.Close();
        // Get the response.  
        WebResponse response = request.GetResponse();
        // Display the status.  
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.  
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.  
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.  
        string responseFromServer = reader.ReadToEnd();
        // Display the content.  
        Console.WriteLine(responseFromServer);
        // Clean up the streams.  
        reader.Close();
        dataStream.Close();
        response.Close();
    }

但它一直让我反应。

  

System.Net.WebException:'远程服务器返回错误:(400)   错误的请求。'

是否可以以这样的格式发送postData?

请求将发送至Zoho - REST API

1 个答案:

答案 0 :(得分:2)

我还不知道您可能遇到的其他问题,但请将您的帖子正文格式化为application/x-www-form-urlencoded。您发送的是HTML,我不相信这是他们的文档的意图。他们向您展示了如何构建HTML表单,而不是如何从代码中获取API。如果您在网页上有这样的表单,则会将其发布到API:

authtoken=12333&scope=creatorapi&criteria=UpdateUj%3d123&Kljuc=1

注意我使用=%3d字符进行了编码。您应该UrlEncode您的所有数据都是安全的。