.NET REST PUT CURL API

2019-08-11 05:40发布

ok I have this curl statement that works

curl -i -u user:pass -H "Accept: application/json" -X POST -d "type=menu&title=HelloWorld" http://127.0.0.1:8000/api/pages/

but I cant get it to work in .net.

I have tried restsharp

   private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            var client = new RestClient("http://127.0.0.1:8000/api/pages/");
            client.Authenticator = new HttpBasicAuthenticator("user", "pass");

            var request = new RestRequest(Method.POST);
            request.AddHeader("Accept", "application/json");


            // add parameters for all properties on an object
            request.AddParameter("type", "menu");
            request.AddParameter("title", "HelloWorld");


            // execute the request
            RestResponse response = client.Execute(request);
            var content = response.Content; // raw content as string
            richTextBox1.Text = content.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

and straight .net

 Private Sub ButtonPost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPost.Click

    address = New Uri("http://127.0.0.1:8000/api/pages")

    ' Create the web request  
    request = DirectCast(WebRequest.Create(address), HttpWebRequest)

    ' Set type to POST  
    request.Method = "POST"
    request.ContentType = "Accept: application/json"

    ' Add authentication to request  
    request.Credentials = New NetworkCredential("user", "pass")

    Dim str As String = "type=men&title=HelloWorld"
    ' Create a byte array of the data we want to send  
    byteData = UTF8Encoding.UTF8.GetBytes(str)

    ' Set the content length in the request headers  
    request.ContentLength = byteData.Length

    ' Write data  
    Try
        postStream = request.GetRequestStream()
        postStream.Write(byteData, 0, byteData.Length)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        If Not postStream Is Nothing Then postStream.Close()
    End Try

    Try
        ' Get response  
        response = DirectCast(request.GetResponse(), HttpWebResponse)

        ' Get the response stream into a reader  
        reader = New StreamReader(response.GetResponseStream())

        ' Console application output  
        RichTextBox1.Text = reader.ReadToEnd()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        If Not response Is Nothing Then response.Close()
    End Try

End Sub

0条回答
登录 后发表回答