I have used Cin 7 Endpoints to Update Order. Here is the link: Cin7 Update Order
and then when calling a api I will have Bad Request error. Here is the code
public string UpdateData(string endpoint, Dispatched saleOrder)
{
string xmlStringResult = string.Empty;
try
{
var req = (HttpWebRequest)WebRequest.Create(endpoint);
req.Method = "PUT";
req.ContentType = "application/json";
req.Credentials = GetCredential(endpoint);
var json = JsonConvert.SerializeObject(saleOrder);
if (!String.IsNullOrEmpty(json))
{
using (var ms = new MemoryStream())
{
using (var writer = new StreamWriter(req.GetRequestStream()))
{
writer.Write(json);
writer.Close();
}
}
}
using (var resp = (HttpWebResponse)req.GetResponse())
{
return resp.StatusDescription + resp.StatusCode;
}
}
catch (Exception ex)
{
AppendError(string.Format("UpdateData catch exception: {0}", ex.Message), LogType.System);
}
return xmlStringResult;
}
Extracting credential
private CredentialCache GetCredential(string url)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(_cred.Username, _cred.Key));
return credentialCache;
}
Here is the json data to update
{"id":2631912,"dispatchedDate":"2018-05-10T11:49:41.6238207+08:00","trackingCode":"6J7010926112","reference":"255552"}
Please help and thank you in advance.
Related
I am facing an issue while making a request to an external web service from a C# code with SSL certificate authentication. Currently I am getting error code 500 Internal Server Error from that web service as response.
C# code to make request object and call it:
public class ERCOTWebRequest
{
string action = #"https://testmisapi.ercot.com/2007-08/Nodal/eEDS/EWS?MarketInfo";
public bool GetReports()
{
try
{
// WebRequestHelper.
var request = CreateSOAPWebRequest();
XmlDocument SOAPReqBody = new XmlDocument();
//SOAP Body Request
string nodalXml = File.ReadAllText(#"C:\Users\test\source\repos\WebRequestHelper\ERCOTWebServiceHelper\XMLFile1.xml");
SOAPReqBody.LoadXml(nodalXml);
using (Stream stream = request.GetRequestStream())
{
SOAPReqBody.Save(stream);
}
//Geting response from request
using (WebResponse Serviceres = request.GetResponse())
{
using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))
{
//reading stream
var ServiceResult = rd.ReadToEnd();
//writting stream result on console
Console.WriteLine(ServiceResult);
Console.ReadLine();
}
}
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public HttpWebRequest CreateSOAPWebRequest()
{
string host = #"https://testmisapi.ercot.com/2007-08/Nodal/eEDS/EWS/";
string certName = #"C:\Users\Test\Downloads\ERCOT_TEST_CA\TestAPI123.pfx";
string password = #"password";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
X509Certificate2Collection certificates = new X509Certificate2Collection();
certificates.Import(certName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(host);
req.AllowAutoRedirect = true;
req.ClientCertificates = certificates;
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Headers.Add("SOAPAction", action);
req.Proxy = WebRequest.GetSystemWebProxy();
//HTTP method
req.Method = "POST";
return req;
}
}
Currently I am getting an error(Error 500: Internal Server error) while trying to make SOAP request. Someone please help.
How would I convert this to HttpClient? What I'm looking to do is submit a Tweet to the Twitter api and get the response as Json. The HttpWebRequest is working fine but I just want to port it to HttpClient. I made an attempt at it in the second code example, but it's not actually sending or receiving the response.
HttpWebRequest request = null;
WebResponse response = null;
string responseCode = String.Empty;
try
{
string postBody = "status=" + EncodingUtils.UrlEncode(status);
request = (HttpWebRequest)HttpWebRequest.Create(resource_url);
request.ServicePoint.Expect100Continue = true;
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.ServicePoint.ConnectionLimit = 1;
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(postBody);
}
}
using (response = request.GetResponse())
{
response.ContentType = "application/json";
responseCode = ((HttpWebResponse)response).StatusCode.ToString();
}
}
catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.NameResolutionFailure)
{
request.Abort();
request = null;
}
throw ex;
}
return responseCode;
This is what I've tried to get it work:
private async Task<string> MakeWebRequest1(string status, string resource_url, string authHeader)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.Credentials = CredentialCache.DefaultCredentials;
clientHandler.PreAuthenticate = true;
clientHandler.AllowAutoRedirect = true;
string responseCode = "";
string postBody = "status=" + EncodingUtils.UrlEncode(status);
var request = new HttpRequestMessage()
{
RequestUri = new Uri(resource_url),
Method = HttpMethod.Post,
};
request.Headers.Add("Authorization", authHeader);
// request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
request.Content = new StringContent(postBody, Encoding.UTF8,"application/x-www-form-urlencoded");//CONTENT-TYPE header
using (HttpClient client = new HttpClient(clientHandler))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
// Stream stuff = await client.GetStreamAsync(resource_url);
using (HttpResponseMessage response = await client.SendAsync(request))
{
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if(response.StatusCode == HttpStatusCode.OK)
{
responseCode = "OK";
}
}
}
clientHandler.Dispose();
return responseCode;
}
enter code here
I've tried to add another parameter to the request and it's always coming back as 401 unauthorized. I'm trying to create a Twitter thread. If I remove the in_reply_to_status_id then it's fine.
data = new Dictionary<string, string> {
["status"] = "#username + status,
["in_reply_to_status_id"] = "1167588690929115136"
};
The Twitter API describes it here https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
Reference You're using HttpClient wrong to understand why a static client is being used.
static Lazy<HttpClient> client = new Lazy<HttpClient>(() => {
HttpClientHandler clientHandler = new HttpClientHandler {
Credentials = CredentialCache.DefaultCredentials,
PreAuthenticate = true,
AllowAutoRedirect = true
};
return new HttpClient(clientHandler);
});
private async Task<string> PostStatusRequestAsync(string status, string resource_url, string authHeader) {
using (var request = new HttpRequestMessage(HttpMethod.Post, resource_url)) {
request.Headers.TryAddWithoutValidation("Authorization", authHeader);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new Dictionary<string, string> {
["status"] = status
};
request.Content = new FormUrlEncodedContent(data);
using (HttpResponseMessage response = await client.Value.SendAsync(request)) {
return response.StatusCode.ToString();
}
}
}
Note the use of the FormUrlEncodedContent for the request body, which will encode and concatenate the data as well as take care of the mime type header
...but it's not actually sending or receiving the response.
Ensure that the above is not invoked as a synchronous blocking call, like .Result, which could cause a deadlock.
For example, an async event handler can be used to make the async call
public async void onButtonClick(object sender, EventArgs args) {
//Non-blocking call
var tweetRequestCode = await PostStatusRequestAsync(TweetText, AuthUtils.GetResourceUrl(), AuthUtils.GetWebRequestHeader()));
//back on UI thread
//...
}
Reference Async/Await - Best Practices in Asynchronous Programming
I am developing application using .net MVC C#. I tried to call rest API of PayPal for save credit card details, my code were working fine but suddenly it starting through 400 Bad Request exception. here is my code,
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/vault/credit-card");
var result = "";
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var loginjson = new JavaScriptSerializer().Serialize(new
{
payer_id = cardDetails.PayerId.Trim(),
type = cardDetails.CardType.Trim(),
number = cardDetails.CardNumber.Trim(),
expire_month = cardDetails.ExpireMonth.Trim(),
expire_year = cardDetails.ExpireYear.Trim(),
first_name = cardDetails.FirstName.Trim()
});
streamWriter.Write(loginjson);
streamWriter.Flush();
streamWriter.Close();
//The code fails when creating the Response here, and go into catch block
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
catch (Exception ex)
{
return ex.GetBaseException().Message;
}
}
}
Can anyone help me out from this error?
Thank you in advance.
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
//my stuff
}
catch (WebException ex)
{
string text = null;
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
return text; //ex.GetBaseException().Message;
}
}
This is changed I have done in my catch block to trace proper error, so it return me that error which I was facing.
I am trying to get the access token for the feed.Below is a code, i used to get the access token.
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
string url = "http://example.net/Token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
try
{
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();//parse token from result
}
catch(Exception ex)
{
}
return "";
}
The error below
"An error occurred while sending the request. The text associated with this error code could not be found.
The server name or address could not be resolved"
is throwing while it executes the below code
HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
Please help me to solve the issue
Try this if you are using POST request
public async Task<string> GetAccessToken()
{
string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
try
{
using (var httpClient = new HttpClient())
{
var request1 = new HttpRequestMessage(HttpMethod.Post, "FeedURL");
request1.Content = new StringContent(postString);
var response = await httpClient.SendAsync(request1);
var result1 = await response.Content.ReadAsStringAsync();
result1 = Regex.Replace(result1, "<[^>]+>", string.Empty);
var rootObject1 = JObject.Parse(result1);
string accessToken = rootObject1["access_token"].ToString();
}
}
catch (Exception ex)
{
}
}
I'm trying use HttpWebRequest, and my BeginGetRequestStream works but it never enters the BeginGetResponse function and i have no idea why.. i've searched for a couple of hours and have not found a solution that works
public void Initialize(IScheduler scheduler)
{
if(_isCloud)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_cloudMappingServer + "/Mapping/GetAllCentralPoints");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ReleaseReadCallback), request);
// Instruct the thread to wait until we resume it
_waitHandle.WaitOne();
_waitHandle.Dispose();
}
}
private void ReleaseReadCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest httpRequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (Stream postStream = httpRequest.EndGetRequestStream(asynchronousResult))
{
using (MemoryStream memStream = new MemoryStream())
{
string queryString = string.Empty;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(queryString);
memStream.Write(bytes, 0, bytes.Length);
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
postStream.Write(tempBuffer, 0, tempBuffer.Length);
}
}
httpRequest.BeginGetResponse(new AsyncCallback(ReleaseResponseCallback), httpRequest);
}
catch (Exception ex)
{
var test = ex;
}
}
private void ReleaseResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest responseRequest = (HttpWebRequest)asynchronousResult.AsyncState;
string responseString = string.Empty;
try
{
using (HttpWebResponse resp = (HttpWebResponse)responseRequest.EndGetResponse(asynchronousResult))
{
using (StreamReader streamRead = new StreamReader(resp.GetResponseStream()))
{
responseString = streamRead.ReadToEnd();
try
{
JsonSerializerSettings settings = new JsonSerializerSettings();
List<CentralPointViewModel> _allCentralPointViewModel = JsonConvert.DeserializeObject<List<CentralPointViewModel>>(responseString, settings);
}
catch (JsonReaderException)
{
responseString = responseString.Replace('\"'.ToString(), string.Empty);
string[] responseArray = responseString.Split(';');
}
catch (JsonSerializationException)
{
responseString = responseString.Replace('\"'.ToString(), string.Empty);
}
}
}
}
catch (Exception ex)
{
}
}
It never enters the ReleaseResponseCallback function! I am able to make my server call but the response never reaches me or I am not properly receiving it.. Any help is appreciated