I am trying to post some json data in c#. So far I have tried two methods. One with HttpWebRequest (which sort of works, more info below) and the other with httpClient (I'd rather use this one).

Method:httpClient

using (HttpClient client = new HttpClient())
{                
    var content = new StringContent(postData, Encoding.UTF8, "application/json");
    var response = await client.PostAsync(url, content);
    responseString = await response.Content.ReadAsStringAsync();
}

Method: HttpWebRequest


    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    myHttpWebRequest.Method = "POST";
    byte[] data = Encoding.ASCII.GetBytes(postData);
    myHttpWebRequest.ContentType = "application/json";
    myHttpWebRequest.ContentLength = data.Length;

    Stream requestStream = await myHttpWebRequest.GetRequestStreamAsync();

    requestStream.Write(data, 0, data.Length);
    requestStream.Close();
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)await myHttpWebRequest.GetResponseAsync();
    Stream responseStream = myHttpWebResponse.GetResponseStream();
    StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
    string pageContent = myStreamReader.ReadToEnd();
    myStreamReader.Close();
    responseStream.Close();
    myHttpWebResponse.Close();

Both give the error: Unable to read data from the transport connection: The connection was closed.

Adding this line to the 2nd method solves the issue.

    myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;

I don't understand why it does though. Is there a way I can do this with httpClient because I'd rather use that. Any help is appreciated. Thanks.

0 Answers