I am trying to insert a new contact in Salesforce using Rest Api but unfortunately getting 400 Bad request exception.While using Postman everything is perfect but via code it is throwing exception. Someone guide me plz where I am wrong.
string new_Contact_url = ConfigurationManager.AppSettings["SalesForceBaseUrl"] + "sobjects/contact";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new_Contact_url);
request.Method = "POST";
request.Headers.Add("Authorization", "Access_Token");
request.ContentType = "application/json; charset=utf-8";
var keyValues = new Dictionary<string, string>
{
{ "LastName", "Nafees" },
{ "Email", "email "},
{ "Tools_User_ID__c", "login_id" }
};
JavaScriptSerializer js = new JavaScriptSerializer();
string postData = js.Serialize(keyValues);
byte[] byteArray = Encoding.UTF8.GetBytes(postData.Trim());
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var resp = reader.ReadToEnd();
var serializer = new JavaScriptSerializer();
var responseBody = (IDictionary<string, object>)serializer.DeserializeObject(resp);
if (!string.IsNullOrEmpty(responseBody["access_token"].ToString()))
{
string id = responseBody["Id"].ToString();
}
Salesforce recently switched from supporting TLS1.0 to TLS1.2.
In your C# code can you add this:
using System.Net;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
The ServicePointManager part should be before you send the request.
Related
Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.
With the following code, I'm trying to post a html form and expecting a complete html page-
string reqString = "destination=&calldate_from=2015-08-01&calldate_to=2015-08-02&call_status=ANSWERED&search=Search";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.100.70:83/report/outgoing/search");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestData.Length;
request.Host = "192.168.100.70:83";
request.Method = "POST";
Cookie idcookie = new Cookie("PHPSESSID", "19fv94lhgtdr80st6ig366q461") { Domain = "192.168.100.70" };
Cookie bdcookie = new Cookie("ciIPPBXOBd", "nMXEiUJiSU%3D") { Domain = "192.168.100.70" };
request.CookieContainer = request.CookieContainer ?? new CookieContainer();
request.CookieContainer.Add(idcookie);
request.CookieContainer.Add(bdcookie);
// Get the request stream.
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestData, 0, requestData.Length);
// requestStream.Flush();
requestStream.Close();
WebResponse response = request.GetResponse();
var res = ((HttpWebResponse)response).StatusDescription; //gets OK here.
StreamReader reader = new StreamReader(response.GetResponseStream());
string returnValue = reader.ReadToEnd(); //found empty
reader.Close();
Code is running without throwing any exception. But I can not retrieve the full html. How can I do that?
I'm trying to post data to a web server with such code:
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
//request.CookieContainer = new CookieContainer();
//request.CookieContainer.Add(new Uri(uri), new Cookie());
string postData = parameters.ToQueryString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
try
{
using (Stream dataStream = await request.GetRequestStreamAsync())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
WebResponse response = await request.GetResponseAsync();
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
return await reader.ReadToEndAsync();
}
}
catch (Exception e)
{
return e.Message + e.StackTrace;
}
Those bits of information that I found on the Internet suggest that it's because response headers are incorrect, but it's not for sure.
Could you please tell how to do http post request with parameters and if suggestion described above is correct, how to tell system.net not to check response headers?
This is how I'm calling this method:
Dictionary<string, string> par = new Dictionary<string, string>();
par.Add("station_id_from", "2218000");
par.Add("station_id_till", "2200001");
par.Add("train", "112Л");
par.Add("coach_num", "4");
par.Add("coach_class", "Б");
par.Add("coach_type_id", "3");
par.Add("date_dep", "1424531880");
par.Add("change_scheme", "0");
debugOutput.Text = await Requests.makeRequestAsync("http://booking.uz.gov.ua/purchase/coach", par);
I want to do a create via a webservice which needs a uri like this:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
my problem is, element is all information of an email with html body, which is about 6000 characters.
I want to call the url like this:
var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
but it breaks at
var response = request.GetResponse();
and says the uri is too long.
I can't change the server's max length of the url and the webservice needs the parameters in the url.
I haven't found a suitable solution for me yet so any help is appreciated.Update:
For anyone facing the same issue, the solution that worked for me was to put my query into an byte-Array like
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
and writing that into the webrequest instead of my queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
You can put data in the body of the request with something a little like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<url>/webservice.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonContent = JsonConvert.SerializeObject(new YourObject
{
// Pseudo code... Replace <...> with your values etc
Operation = <YourOperation>,
ElementType = <YourElementType>,
Element = <YourElement>,
// etc...
});
HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync("youroperation/", httpContent);
}
// Do something with response if you want
}
This is JSON based but could be anything you want to pass... This is a simple example that will hopefully give you an idea of how you can proceed.
You need to split the urlToUse at the question mark:
Something like this (not tested)
string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
Good luck with your quest.
I am trying to add a member to a group using the aad graph api and I am keep getting 404.
A similar code works for me when I am trying to get the group members.
This is the code:
string requestUrl = string.Format("https://graph.windows.net/{0}/groups/{1}/$linkes/members?api-version=2013-04-05", tenantName, group.ObjectId);
string postData = string.Format("\"url\":\"https://graph.windows.net/{0}/users/{1}?api-version=2013-04-05\"", tenantName, user.ObjectId);
HttpWebRequest webRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = authenticationResult.CreateAuthorizationHeader();
webRequest.ContentType = "application/json"; //"application/x-www-form-urlencoded";
webRequest.Host = "graph.windows.net";
webRequest.ContentLength = postData.Length;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
string jsonText;
var httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (var streamReader =
new StreamReader(httpResponse.GetResponseStream()))
{
jsonText = streamReader.ReadToEnd();
}
I know there are other ways to do the same work, for example using the graph connection, but I prefer to use this way because it should work for roles as well.
Thanks
Your URL does seem to have a typo: $linkes. Should be $links.