I have called an API request and serialized the response using RESTSHARP.
However, when im deserializing it's throwing the error
Error MSG Data at the root level is invalid. Line 1, position 1.
I know that the correct value has been serialized because in my console.WriteLine section it displays the auth token that i need to pull out.
Here is my code:
static void Main(string[] args)
{
var URL = "****/login/";
IRestClient restClient = new RestClient();
IRestRequest restRequest = new RestRequest(URL);
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddParameter("application/json", "{\r\n \"UserName\": \"****\",\r\n \"Password\": \"*****\"\r\n}", ParameterType.RequestBody);
IRestResponse restResponse = restClient.Post(restRequest);
if (restResponse.IsSuccessful)
{
Console.WriteLine("Status Code " + restResponse.StatusCode);
Console.WriteLine("Response Content " + restResponse.Content);
JsonDeserialize();
}
}
public static void JsonDeserialize()
{
var URL = "****/login/";
IRestClient restClient = new RestClient();
IRestRequest restRequest = new RestRequest(URL);
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddParameter("application/json", "{\r\n \"UserName\": \"****\",\r\n \"Password\": \"****\"\r\n}", ParameterType.RequestBody);
IRestResponse<List<MySuilvisionAuth>> restResponse = restClient.Post<List<MySuilvisionAuth>>(restRequest);
if (restResponse.IsSuccessful)
{
Console.WriteLine("Status Code " + restResponse.StatusCode);
Console.WriteLine("Response Content " + restResponse.Data.Count);
}
else
{
Console.WriteLine("Error Msg " + restResponse.ErrorMessage);
Console.WriteLine("Stack Trace " + restResponse.ErrorException);
}
Related
I can accomplish all other tasks with the rest API, like uploading and downloading files, navigating through the file directory. I just keep getting either 400 Bad Request or sometimes with some tries I'll get 500 Internal Server Error. Also, I can create the request on postman and its successful
this is what the request should look like the rest is me creating it in c#
POST https://{site_url}/_api/web/folders
Authorization: "Bearer " + accessToken
Accept: "application/json;odata=verbose"
Content-Type: "application/json"
Content-Length: {length of request body as integer}
X-RequestDigest: "{form_digest_value}"
{
"__metadata": {
"type": "SP.Folder"
},
"ServerRelativeUrl": "/document library relative url/folder name"
}
private async Task PostFolderSharePoint(string url, string serverRelativeUrl)
{
string accessToken = GetAccessToken().GetAwaiter().GetResult();
string jsoncontent = JsonConvert.SerializeObject("{\"__metadata\": {\"type\": \"SP.Folder\"},\"ServerRelativeUrl\": serverRelativeUrl}");
var content = new StringContent(jsoncontent, Encoding.UTF8, "application/json");
var FormDiGestValue = await GetFormDigestValue(accessToken);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var requestMessage = new HttpRequestMessage(HttpMethod.Post,url) { Content = content };
requestMessage.Headers.Add("X-RequestDigest", FormDiGestValue);
HttpResponseMessage response = await _httpClient.SendAsync(requestMessage).ConfigureAwait(false);
return response;
}
This is how I create a folder with the Sharepoint REST API:
public async Task<string> CreateFolder(string folderName, string relativeUrl)
{
try
{
var url = "https://your.sharepoint.com/sites/devsite/_api/web/folders";
var json = "{\"ServerRelativeUrl\": \"" + relativeUrl + "/" + folderName + "\"}";
var payload = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-User-Agent", "spoc");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.PostAsync(url, payload);
return await response.Content.ReadAsStringAsync();
}
catch (WebException we)
{
throw new SomethingException(we);
}
}
and to use it:
var modFolder = await spocRest.CreateFolder("MOD1", "Shared Documents");
I'm trying to make HTTP request with Bearer authorization. I have a token, token is valid. Tried to do it 3 different ways: App, that request must be implemented in, POSTMAN, console app with a code generated with POSTMAN (C# - RestSharp) from the same POSTMAN call:
App POST method:
public async Task<TResponse> Post<TRequest, TResponse>(string requestUri, TRequest data)
{
LogInit(requestUri, HttpMethod.Post, data);
using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
{
var token = await GetToken(_httpClient);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
request.Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
using (var response = await _httpClient.SendAsync(request))
{
if (!response.IsSuccessStatusCode)
{
throw await HandleErrorResponse(response);
}
var responseObj = await response.Content.ReadAsJsonAsync<TResponse>();
return responseObj;
}
}
}
Console POST method:
static void Main(string[] args)
{
var client = new RestClient("http://***");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer xxx");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "ARRAffinity=xxx");
var body = #"{
" + "\n" +
#" ""amisPersonId"": ***,
" + "\n" +
#" ""name"": ""***"",
" + "\n" +
#" ""surname"": ""***"",
" + "\n" +
#" ""personalCode"": ""***"",
" + "\n" +
#" ""email"": ""***"",
" + "\n" +
#" ""phoneNumber"": ""***""
" + "\n" +
#"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
Requests tracked with debugger:
App request
Console app request
POSTMAN request
POSTMAN gets 200/400 reponses, App and Console app gets 401 (Unauthorized). BOTH Apps are .NET CORE apps.
assuming that you have correct token.AccessToken ,try to replace
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
with
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
below codes is the generated c# restsharp codes from postman. How can I convert it to c# asp.net mvc4 codes for httpclient. When trying to debug in VS, I always have error of bad request. This is for ebay api creating a shipping fulfillment. Tested in postman works with the codes below.
var client = new RestClient("https://api.ebay.com/sell/fulfillment/v1/order/23-00000-11313/shipping_fulfillment");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Content-Language", "en-US");
request.AddHeader("Accept-Language", "en-US");
request.AddHeader("Accept-Charset", "utf-8");
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", "Bearer v^1.1#i^1#I^3#f^0#p^3#r^0#t^H4sIAAAAA==");
request.AddParameter("application/json", "{\"lineItems\":[{\"lineItemId\":\"10022882297723\",\"quantity\":1}],\"shippedDate\":\"2020-02-11T01:28:16.475Z\",\"shippingCarrierCode\":\"Couriers Please\",\"trackingNumber\":\"UHV3436755010009000000\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Current codes in asp.net but having error bad request.
private HttpClient CreateHttpClient()
{
var client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string baseAddress = WebApiBaseAddress;
if (string.IsNullOrEmpty(baseAddress))
{
throw new HttpRequestException("There is no base address specified in the configuration file.");
}
client.Timeout = new TimeSpan(0, 5, 59);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", _cred.eBayToken));
client.DefaultRequestHeaders.Add("Accept-Language", "en-US");
client.DefaultRequestHeaders.Add("Accept-Charset", "utf-8");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("LegacyUse", "true");
return client;
}
public HttpResponseMessage PostHttpResponse(string requestUri, object data)
{
var stringPayload = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.Add("Content-Language", "en-US");
httpContent.Headers.Add("Content-Encoding", "gzip");
using (var client = CreateHttpClient())
{
try
{
HttpResponseMessage response = client.PostAsJsonAsync(requestUri, httpContent).Result;
if (response.IsSuccessStatusCode)
{
return response;
}
else
{
GetErrorsResponse(response);
throw new HttpRequestException(string.Format("There was an exception trying to post a request. response: {0}", response.ReasonPhrase));
}
}
catch (HttpRequestException ex)
{
throw ex;
//return null;
}
}
}
Thank in advance for the help. It is very much appreciated.
I'm using restsharp to make rest api client. This is my code:
var client = new RestClient("https://url.com");
client.Authenticator = new SimpleAuthenticator("client_id", "testapi", "client_secret", "password");
var request = new RestRequest("webapi/rest/auctions", Method.GET);
request.AddParameter("limit", "10");
request.AddParameter("order", "auction_id");
request.AddParameter("page", "1");
request.AddParameter("offset", "0");
IRestResponse response = client.Execute(request);
Console.WriteLine("request: " + response.Content);
Response is always: {"error":"unauthorized_client"}
And here is information from documentation of this rest api
I've been trying to use RestSharp Library in order to make requests, but when I've tried to make a POST request this error keeps emerging!!
Here is the code:
private readonly string contentType = "application/json";
try
{
var restClient = new RestClient(new Uri(InvoiceExpressURLS.URL_createClient));
string clientJsonRequest =
JsonConvert.SerializeObject(
JsonConvert.DeserializeObject("{\"client\":" + JsonConvert.SerializeObject(newClient) + "}")
);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", contentType);
request.AddJsonBody(clientJsonRequest);
var restResponse = await restClient.ExecuteTaskAsync<object>(request);
if (restResponse.IsSuccessful)
{
response.responseObject = restResponse.Data;
response.responseMessage = string.Format("The client \"{0}\" was successfuly created.", newClient.name);
}
else
{
response.responseStatus = restResponse.StatusCode;
response.responseMessage = restResponse.ErrorMessage;
}
}
catch (Exception e)
{
response.responseStatus = HttpStatusCode.InternalServerError;
response.responseMessage = e.Message;
response.responseObject = e;
}