Getting Unsupported Media Format in HttpClient when calling Get Method api using with proxy, - proxy

I could able to get the response from postman by providing proxy, bearer,X-IBM-Client-Id,"X-IBM-Client-Secret for get request but when i try the same with httpclient , I am getting the response as Unsupported Media Format
var proxy = new WebProxy
{
Address = new Uri($"http://proxy.proxyaddress.com:8080"),
BypassProxyOnLocal = false,
UseDefaultCredentials = false,
};
var httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
};
httpClientHandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
var client = new HttpClient(httpClientHandler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
client.DefaultRequestHeaders.Add("X-IBM-Client-Id", clientID);
client.DefaultRequestHeaders.Add("X-IBM-Client-Secret", clientSecret);
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
client.DefaultRequestHeaders.Add("Accept", "application/json");
var message = new HttpRequestMessage(HttpMethod.Get, endPointURL);
HttpResponseMessage response = await client.SendAsync(message);

Related

although i have a token, xamarin gives 401 error, wher is problem

although, i have a token xamarin gives 401 error when i post to rest api, or get..have you any solution ?
public async Task<List<Gorev>> GetGorevlerAsync(Gorev Gorev, string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = JsonConvert.SerializeObject(Gorev);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string uri = Constants.BaseApiAddress + "http/GorevTeamLstStored";
var ReturnJson = await client.PostAsync(uri, content);
var ls = ReturnJson.Content.ReadAsStringAsync().Result;
var Gorevler = JsonConvert.DeserializeObject<List<Gorev>>(ls);
return Gorevler;
.
}

Dynamics WEB API returns on post -StatusCode: 401, ReasonPhrase: 'Unauthorized'

I am trying to create a lead in CRM from via web api , but its throwing unauthorized access error. I am able to login to CRM but from Web Api , It's throwing error
Below is my code
var credentials = new NetworkCredential("username", "password");
var client = new HttpClient(new HttpClientHandler() { Credentials = credentials })
{
BaseAddress = new Uri("https://*******.dynamics.com/XRMServices/2011/Organization.svc/api/data/v8.2/")
};
Entity lead1 = new Entity();
lead1["firstname"] = "TestFirstName";
lead1["lastname"] = "TestLastName";
lead1["emailaddress1"] = "%%%%%%%%%";
lead1["companyname"] = "&&&&&&";
string output = new JavaScriptSerializer().Serialize(lead1).ToString();
HttpRequestMessage request = null;
try
{
request = new HttpRequestMessage(HttpMethod.Post, "leads");
request.Content = new StringContent(output);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
Task<HttpResponseMessage> response = client.SendAsync(request);
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
//retrievedContact1 = JsonConvert.DeserializeObject<JObject>(rep .Content.ReadAsStringAsync());
}

Null response Xamarin android application using web api

Hi I am just learning Xamarin android development and I just want to CRUD operation but I am stuck that I am unable to get any response from webapi. I have tested my api using SOAPUI and response is ok from that.
[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
if (value != "1234")
{
string json = #"{ data: 'Emp Code is not valid.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
else
{
string json = #"{ data: 'data save sucessfully.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
}
this is api code and below is my android application code but I am getting null response exception.
public async Task SaveTodoItemAsync(string EmpCode)
{
try
{
string url = "http://192.168.1.9/attandanceapi/api/attandance?value=12132";
var uri = new Uri(string.Format(url));
var json = JsonConvert.SerializeObject(EmpCode);
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(url, content);
var responses = response;
}
catch (Exception ex)
{
var w = ex.ToString();
}
}
I think we have problem here. You are trying to create content from string not from Json.
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
try this:
var content = new StringContent(json, Encoding.UTF8, "application/json");
Edit:
I cannot see your default headers so if you don't have them - just add.
client.DefaultRequestHeaders.Add("Accept", "application/json");

PayPal Rest API webhook signature verification always return verification_status as FAILURE

I have paypal integration application which receives webhook notification from paypal and I want to verify the signature as per docs:
Verify signature rest api link
Here is code which I have written:
public async Task<ActionResult> Index()
{
var stream = this.Request.InputStream;
var requestheaders = HttpContext.Request.Headers;
var reader = new StreamReader(stream);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
var webhook = serializer.Deserialize<Models.Event>(jsonReader);
var webhookSignature = new WebhookSignature();
webhookSignature.TransmissionId = requestheaders["PAYPAL-TRANSMISSION-ID"];
webhookSignature.TransmissionTime = requestheaders["PAYPAL-TRANSMISSION-TIME"];
webhookSignature.TransmissionSig = requestheaders["PAYPAL-TRANSMISSION-SIG"];
webhookSignature.WebhookId = "My actual webhookid from paypal account";
webhookSignature.CertUrl = requestheaders["PAYPAL-CERT-URL"];
webhookSignature.AuthAlgo = requestheaders["PAYPAL-AUTH-ALGO"];
webhookSignature.WebhookEvent = webhook;
var jsonStr2 = JsonConvert.SerializeObject(webhookSignature);
var result = await _webhookService.VerifyWebhookSignatureAsync(webhookSignature);
var jsonStr3 = JsonConvert.SerializeObject(result);
return Content(jsonStr3, "application/json");
}
public async Task<Models.SignatureResponse> VerifyWebhookSignatureAsync(Models.WebhookSignature webhook, CancellationToken cancellationToken = default(CancellationToken))
{
var accessTokenDetails = await this.CreateAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessTokenDetails.AccessToken);
try
{
string jsonStr = JsonConvert.SerializeObject(webhook);
var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
string url = $"{_baseUrl}notifications/verify-webhook-signature";
var response = await _httpClient.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new Exception(error);
}
string jsonContent = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<Models.SignatureResponse>(jsonContent);
}
catch (Exception ex)
{
throw new InvalidOperationException("Request to Create payment Service failed.", ex);
}
}
Webhook signature verification response :
{"verification_status":"FAILURE"}
I am getting 200K ok response from api but verification status in response is always FAILURE.I tried many different request.
I am not sure if something is wrong from my request. Looking for help.

wp7 - POST http request with parameters in request body using RestSharp

I am trying to POST parameters through the request, to a service that returns a JSON object. The service works well for android and iOS. I am trying to get this working for wp7. The service requires the content type to be 'application/json' I have pasted the code that sets up the http request below:
var client = new RestClient(baseurl);
var request = new RestRequest();
request.Resource = "login";
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.AddHeader("content-type", "application/json");
request.RequestFormat = DataFormat.Json;
var postData = new Dictionary<string, string>()
{
{"key1",value1},
{"key2",value2}
};
request.AddBody(postData);
client.ExecuteAsync(request, response =>
{
var jsonUser = response.Content;
});
The response error I get from the server is an internal server error. Is anything wrong with the code above. I also tried request.AddParameter method but ended with the same result. The code for that is below:
var client = new RestClient(baseurl);
var request = new RestRequest();
request.Resource = "login";
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.AddHeader("content-type", "application/json");
request.RequestFormat = DataFormat.Json;
var postData = new Dictionary<string, string>()
{
{"key1",value1},
{"key2",value2}
};
var json = JsonConvert.SerializeObject(postData);
request.AddParameter("application/json", json, ParameterType.RequestBody);
client.ExecuteAsync(request, response =>
{
var jsonUser = response.Content;
});
Is there anything that I am doing wrong in either of the cases?

Resources