C# HttpWebRequest of type application/x-www-form-urlencoded - how to send '&' character in content body?
Since your content-type is application/x-www-form-urlencoded
you'll need to encode the POST body, especially if it contains characters like &
which have special meaning in a form.
Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.
Here are a couple links for reference.
- http://en.wikipedia.org/wiki/Percent-encoding
How to pass header and Body value using HttpWebRequest in C#?
Here is correct HttpWebRequest
using:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
request.Method = "POST";
string postData = "grant_type=client_credentials&client_id=ruban123&client_secret=123456";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
HttpWebRequest approach is not relevant. Look at this question Setting Authorization Header of HttpClient
x-www-form-urlencoded in Xamarin
i have used the following code for authenticating user in my project might help you.
public static async Task<UserData> GetUserAuth(UserAuth userauth)
{
bool asd= CheckNetWorkStatus().Result;
if (asd)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);// ("http://192.168.101.119:8475/");
var postData = new List<KeyValuePair<string, string>>();
var dto = new UserAuth { grant_type = userauth.grant_type, password = userauth.password, username = userauth.username };
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("grant_type", userauth.grant_type));
nvc.Add(new KeyValuePair<string, string>("password", userauth.password));
nvc.Add(new KeyValuePair<string, string>("username", userauth.username));
var req = new HttpRequestMessage(HttpMethod.Post, UrlAdd + "token") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
var userData = JsonConvert.DeserializeObject<UserData>(result);
userData.ErrorMessage = "true";
return userData;
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Incorrect Password";
return ud;
}
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Check Ur Connectivity";
return ud;
}
}
How to post data to specific URL using WebClient in C#
I just found the solution and yea it was easier than I thought :)
so here is the solution:
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1¶m2=value2¶m3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
it works like charm :)
C# HttpWebRequest Post form data with special string
Wrap all your data with System.Web.HttpUtility.UrlEncode.
string strNew = "&it=" + it + "&tipo_new=1&id=" + inputValue + "&monto=0&mon=";
strNew = System.Web.HttpUtility.UrlEncode(strNew);
RestSharp post request - Body with x-www-form-urlencoded values
this working for me, it was generator from postman
var token = new TokenValidation()
{
app_id = CloudConfigurationManager.GetSetting("appId"),
secret = CloudConfigurationManager.GetSetting("secret"),
grant_type = CloudConfigurationManager.GetSetting("grant_type"),
Username = CloudConfigurationManager.GetSetting("Username"),
Password = CloudConfigurationManager.GetSetting("Password"),
};
var client = new RestClient($"{xxx}{tokenEndPoint}");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"app_id={token.app_id}&secret={token.secret}&grant_type={token.grant_type}&Username={token.Username}&Password={token.Password}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Access Token cannot obtain, process terminate");
return null;
}
var tokenResponse = JsonConvert.DeserializeObject<TokenValidationResponse>(response.Content);
Proper way to handle the ampersand character in JSON string send to REST web service
The problem was that I was encoding the whole request string including the key.
I had a request data={JSON}
and I was formatting it, but the {JSON}
part should only be encoded.
string requestData = "data=" + Uri.EncodeDataString(json) // worked perfect!
Stupid hole to step into.
Related Topics
Internal .Net Framework Data Provider Error 1025
Capturing Process Output via Outputdatareceived Event
Client Id for Property (ASP.NET MVC)
Uniquely Identifying Reference Types in the Debugger
Dynamically Create a Generic Type for Template
Reverse Sorted Dictionary in .Net
How to Compare Two Images Using Byte Arrays
What Does "Displayclass" Name Mean When Calling Lambda
Epplus Large Dataset Issue with Out of Memory Exception
How to Have a Variable Number of Generic Parameters
Alternative to Findmimefromdata Method in Urlmon.Dll One Which Has More Mime Types
Monitor Process Start in the System
Equality Comparison Between Multiple Variables
The Operation Cannot Be Completed Because the Dbcontext Has Been Disposed Error