Reputation:
How can I make an HTTP request and send Json data with Headers and read the response?
The third party had provided some credentials to use their API. Using those credentials I need to invoke the API and read the response. I need to send a header named SIGNATURE along with the request data. The value of the signature is the Encrypted Request data.
I can do the POST request but have no idea how to add the Header.
My code is like this
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URL");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("SIGNATURE", sEncrypteddata)
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"id\":\"2423432432\"," +
"\"uid\":\"id123\","+
"\"pwd\":\"pass\","+
"\"apiKey\":\"2423432432\","+
"\"paymentCategory\":0"+
"\"paymentType\":0}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
}
is this is the correct way ?
Upvotes: 0
Views: 1204
Reputation: 1843
You have to Move Headers before the request steam works, because the request stream is adding the body.
Webrequest is implemented internally, before writing Body finish with Header, and once its in stream format, its ready to send.
The implementation of webrequest in reflector or some such decompiling tool, you ca find the logic.
Upvotes: 0
Reputation: 2806
I assume that you use the HttpClient
class.
This class has a property called DefaultRequestHeaders
.
All header information within this property should be sent with each request that you do with the instance.
httpClient.DefaultRequestHeaders.Add("SIGNATURE", "your value");
Upvotes: 1