HTTP Post request with custom header

42,680

Solution 1

Use WebRequest.ContentType property. Some headers can be set using API properties only.

EDIT:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.androidlost.com/androidlost/greet");
request.ContentType = "text/x-gwt-rpc; charset=utf-8";

Solution 2

According to the MSDN documentation, HttpWebRequest.Header Property.

The Content-Type are modified using the ContentType property. This requires that you cast the WebRequestto HttpWebRequest

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.androidlost.com/androidlost/greet");
Share:
42,680
Antonio
Author by

Antonio

Updated on June 22, 2020

Comments

  • Antonio
    Antonio almost 4 years

    I want to make a HTTP Post request from C#. This request has a custom headers. When I try to start my program I received this exception:

    Italian:

    Questa intestazione deve essere modificata utilizzando la proprietà o il metodo appropriato. Nome parametro: name

    English:

    This header must be modified using the appropriate property or method.

    On line: request.Headers.Add("Content-Type", "text/x-gwt-rpc; charset=utf-8");

    This is my code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Collections.Specialized;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.Dynamic;
    using System.Collections;
    using System.Collections.ObjectModel;
    using System.Net.Security;
    using System.Web;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                WebRequest request = WebRequest.Create("http://www.androidlost.com/androidlost/greet");
                request.Method = "POST";
                request.Headers.Add("Content-Type", "text/x-gwt-rpc; charset=utf-8");
                string postData = "Test";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
             }
        }
    }
    

  • Antonio
    Antonio almost 12 years
    thanks andy... please write me a snippet of code to resolve the problem... regards