Send graphql to the Post body in Restsharp automation - graphql

throwing the below error when I pass GraphQL to the AddParameter#
{"errors":[{"message":"Expected \u0060{\u0060 or \u0060[\u0060 as first syntax token.","locations":[{"line":1,"column":1}],"extensions":{"code":"EXEC_SYNTAX_ERROR"}}]}
RestClient restClient = new RestClient("https://xxxxxx");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + AccessToken);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/graphql","{\"query\":\"{\\n agreements(where : submissionId:\\\"180823\\\") }" + ParameterType.RequestBody);
var resp = restClient.Execute(request);

I had similar issue when using HttpClient. Solved by UTF8 encode the query.
var gql = #"{""query"": ""{something { field1, field2 } }""}";
var message = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxx/graphql")
{
Headers =
{
{"Authorization", token}
},
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(gql))
{
Headers =
{
{"Content-Type", "application/json"}
}
}
};

Related

Getting Ansible Tower API authentication token from C#

I tried using this C# code below, but getting status code 401 (reason:unautherized):
var baseUri = "https://ansibletower1.test1.com";
var data = #"{'username':'test123', 'password':'a1b2c3Z0!-99', 'description':'Ansible Api token', 'scope':'write'}";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
Try-2: Using Basic Authorization header.. getting same error (401- unautherized).
I tried from python script, it works. Used Basic Authorization header in it.
var baseUri = "https://ansibletower1.test1.com";
var jsonObject = new {description = "Tower API token", scope = "write" };
var username="test123";
var password="a1b2c3Z0!-99";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{username}:{password}")));
var content = new StringContent(JsonConvert.SerializeObject(jsonObject), Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
I figured out. The url "api/v2/tokens" is missing "/" at the end.
It should be:
var response = httpClient.PostAsync("api/v2/tokens/", content).Result;

How to upload image to server with Flutter

I am trying to upload image to a server.
I have tested the API using postman and it is working correctly.
I found following type of code in many sites but for some reason it is not working for me.
I get 400 status code error.
Can anyone point out what I am doing wrong?
var url = serverUrl + "/users/profile/upload-pic";
String basicAuth = 'Bearer ' + auth.token;
var postUri = Uri.parse(url);
var request = new http.MultipartRequest("POST", postUri);
request.headers['authorization'] = basicAuth;
request.files.add(
new http.MultipartFile.fromBytes(
'file',
await file.readAsBytes(),
contentType: new MediaType('image', 'jpeg'),
),
);
final response = await request.send();
print('Response status: ${response.statusCode}');
Upload(File imageFile) async {
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
String basicAuth = 'Token ' + auth.token; // you have to use Token while parsing Bearer token
var uri = Uri.parse(serverUrl + "/users/profile/upload-pic");
uri.headers['authorization'] = basicAuth;
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Use Dio package and send data with FormData.
For example:
Future<dynamic> _uploadFile(rawFilePath) async {
final filebasename = p.basename(rawFilePath);
var response;
try {
FormData formData = new FormData.fromMap({
"image_id": 123456,
"imageFile": await MultipartFile.fromFile(rawFilePath, filename: filebasename),
});
var url = serverUrl + "/users/profile/upload-pic";
var dio = Dio();
response = await dio.post(url , data: formData );
print('Response status: ${response.statusCode}');
} catch (e) {
print("Error reason: $e");
}
return response;
}

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;
.
}

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");

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