I'm executing curl graph api using c#.
I took my curl query used this website and convert it into c#.
https://curl.olsh.me/
Api is able to give 200 ok status code and but output is below-
{
"extensions" : {
"requestId" : "123"
},
"data" : null,
"errors" : [ {
"message" : "Unable to process JSON",
"extensions" : {
"errorType" : "developer_error",
"errorClass" : "VALIDATION"
}
} ]
}
result string conv: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: keep-alive
Braintree-Version: 2016-10-07
Strict-Transport-Security: max-age=31536000; includeSubDomains
Vary: Braintree-Version
X-Cache: Miss from cloudfront
X-Amz-Cf-Pop: MIA3-C2
X-Amz-Cf-Id: 111
Date: Tue, 10 Sep 2019 16:13:54 GMT
Via: 1.1 demo.cloudfront.net (CloudFront)
Content-Length: 286
Content-Type: application/json
}
C# code -
HttpClientHandler handler = new HttpClientHandler()
{
UseProxy = false,
};
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://demo/graphql"))
{
// Prod token
request.Headers.TryAddWithoutValidation("Authorization", "Basic abc");
request.Headers.TryAddWithoutValidation("Braintree-Version", "2019-01-01");
request.Content = new StringContent("{\"query\": \"{ report { transactionLevelFees(date: \"2019-08-28\"){ url } } }\" }", Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.SendAsync(request);
// Get the response content.
HttpContent responseContent = response.Content;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine((await reader.ReadToEndAsync()));
}
Console.WriteLine($"result string conv: {response }");
}
}
I expect in output i should get something in data json
Related
I have a Web API which uploads the File content to the server.
[HttpPost]
[Route("SaveFileContent")]
public async Task<FileResponse> SaveFileContent([FromForm] SaveFileContentRequest request)
{
return await _service.SaveFile(request);
}
This is my call to the API:
public async Task<FileResponse> SaveFileContent(SaveFileContentRequest request)
{
try
{
var uri = "https://www.mycompanyurl.com";
using (var client = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (var fileContent = new ByteArrayContent(request.File))
{
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent, "file", request.FileName);
form.Add(new StringContent(request.MemberId), "MemberId);
form.Add(new StringContent(request.Country), "Country);
client.BaseAddress = new Uri(uri);
HttpResponseMessage response = await client.PostAsync("/api/Document/SaveFileContent", form);
FileResponse result = JsonConvert.DeserializeObject<FileResponse>(response.Content.ReadAsStringAsync().Result);
return result;
}
}
}
}
}
I get this response at PostAsync():
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Sun, 21 Apr 2013 12:00:03 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 165
Content-Type: application/json; charset=utf-8
}}
When I try to run the API in my local - and use the localhost uri -
var uri = "http://localhost:51515";
It is working fine and getting the 200 OK response.
try to use the full route
[Route("~/api/Document/SaveFileContent")]
public async Task<FileResponse> SaveFileContent([FromForm] SaveFileContentRequest request)
When I run this from a browser manually, it returns a response, that looks like this:
{"value":[{"ID":4}]}
Now, I am POSTing it from a Windows IoT Device, using the following code:
private async Task SendPostRequest(string username, string password, Dictionary<string, string> parameters)
{
try
{
// using Windows.Web.Http
HttpFormUrlEncodedContent formattedData = new HttpFormUrlEncodedContent(parameters);
using (HttpBaseProtocolFilter clientHandler = new HttpBaseProtocolFilter())
{
clientHandler.ServerCredential = GetCredentials(username, password);
using (HttpClient httpClient = new HttpClient(clientHandler))
{
//txtCommand.Text = "PostAsync";
HttpResponseMessage response = await httpClient.PostAsync(postUrl, formattedData);
txtResponse.Text = response.ToString();
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
txtResponse.Text += " responseString: " + responseString;
}
}
The result in responseString is an empty string.
The result of response.ToString() looks like this:
StatusCode: 200, ReasonPhrase: 'OK', Version: 2, Content: Windows.Web.Http.HttpStreamContent, Headers:
{
Persistent-Auth: true
Server: Microsoft-IIS/10.0
Transfer-Encoding: chunked
Date: Fri, 27 Aug 2021 15:16:38 GMT
X-Powered-By: ASP.NET
dbgate-version: 1.0
}{
Content-Type: text/plain
}
I am trying to post captured image from WPF to WebApi method using HttpClient but i am getting 400 BAD REQUEST error.
I have tried in google but unable to resolve the issue. does anyone help me.
Below is the code in WPF
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
string FileName =
System.IO.Path.GetFullPath("../../captured_images") +
"//captured_image" + DateTime.Now.Day.ToString() +
DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() +
DateTime.Now.Second.ToString() + ".jpg";
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)image.Source));
using (FileStream stream = new FileStream(FileName,
FileMode.Create))
encoder.Save(stream);
string CASAAuthResponse = await
CASSecurity.GetAuthenticationToken();
CASAuthTokenResponse techSeeTokenResponse =
JsonConvert.DeserializeObject<CASAuthTokenResponse>
(CASAAuthResponse);
HttpContent fileStreamContent = new StreamContent(File.OpenRead(FileName));
using (var client1 = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
client1.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
formData.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
formData.Add(fileStreamContent, "face",
Path.GetFileName(FileName));
var response = await
client1.PostAsync(CASIdentifyFaceUrl, formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
}
}
Server Web api:
[HttpPost]
[Route("identify")]
public async Task<IActionResult> Identify(IFormFile face)
{
Guid temporaryUsername = Guid.Empty;
using (var faceStream = face.OpenReadStream())
{
temporaryUsername = await verifyBusiness.IdentifyUser(faceStream,
new Guid(Requester.ClientId));
}
return Ok(temporaryUsername);
}
And i am getting error as descibed below:{StatusCode: 400,
ReasonPhrase: 'Bad Request', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Transfer-Encoding: chunked
Strict-Transport-Security: max-age=2592000 Date: Thu, 20 Jun 2019
11:13:28 GMT Set-Cookie:
ARRAffinity=4cbc3e777eee0146fcbb9f695794b29417cc953731f6f8f581457a1d7cd7aa14;Path=/;HttpOnly;Domain=cas-qa.tempdata.net
Server: Kestrel X-Powered-By: ASP.NET Content-Type:
application/json; charset=utf-8 }}
I'm getting a "Bad Request" when I try to create a new OneNote API Notebook.
private async Task<string> CreateSimpleNotebook(string notebookName, string apiRoute)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
catch (Exception ex)
{
string tempEx = ex.ToString();
}
var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute )
{
Content = new StringContent("{ name : '" + WebUtility.UrlEncode(notebookName) + "' }", Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await client.SendAsync(createMessage);
return response.Headers.Location.ToString();
}
And I call the method with the following:
string url = "https://graph.microsoft.com/v1.0/me/onenote/notebooks/";
// string url = "https://www.onenote.com/api/v1.0/me/notes/notebooks/";
string tempResponse = await CreateSimpleNotebook("EMRTest2", url);
Here is the response:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
client-request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
request-id: acacd4f5-8738-4c46-8150-17aa23413eb5
Transfer-Encoding: chunked
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"South Central US","Slice":"SliceB","Ring":"NA","ScaleUnit":"002","Host":"AGSFE_IN_10","ADSiteName":"SAN"}}
Duration: 772.4124
Cache-Control: private
Date: Sun, 19 Nov 2017 20:59:10 GMT
Content-Type: application/json
}}
You should use Content-Type JSON
The name of the property you are looking for is not "name", it is "displayName"
Additionally, crafting JSON by appending string is not best practice - I recommend using a JSON library, like NewtonSoft JSON.NET.
I'm looking for solution to send request with JSON like parameter to server.
I use this code,
var httpClient = new HttpClient();
var tempByteArray = Encoding.UTF8.GetBytes("my valid json");
var stream = new MemoryStream(tempByteArray);
var streamContent = new StreamContent(stream);
var request = new HttpRequestMessage(HttpMethod.Post, Constants.LocalServer);
request.Content = streamContent;
request.Headers.TransferEncodingChunked = true;
HttpResponseMessage response = await httpClient.SendAsync(request);
But in response I get:
{
StatusCode: 501,
ReasonPhrase: 'NotImplemented',
Version: 1.0,
Content: System.Net.Http.StreamContent,
Headers: {
X-Squid-Error: ERR_UNSUP_REQ0X-Cache: MISSfromproxy3.itos.orgX-Cache-Lookup: NONEfromproxy3.companyname.org: portProxy-Connection: closeDate: Thu,
18Apr201309: 17: 53GMTServer: squid/2.6.STABLE21Via: 1.0proxy3.companyname.org: port(squid/2.6.STABLE21)Content-Length: 1099Content-Type: text/htmlExpires: Thu,
18Apr201309: 17: 53GMT
}
}
May be have another way to sent request with json parameter on Win8?
UPDATE I found solution:
public static async Task<string> LoadData(string json, string serverUrl)
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.LocalServer));
request.ContentType = "application/json";
request.Method = "POST";
using (var requestStream = await request.GetRequestStreamAsync())
{
var writer = new StreamWriter(requestStream);
writer.Write(json);
writer.Flush();
}
using (var resp = await request.GetResponseAsync())
{
using (var responseStream = resp.GetResponseStream())
{
var reader = new StreamReader(responseStream);
return = reader.ReadToEnd();
}
}
}
It's work great, but must exists more simple way(i hope). And I'll try to find it.
When I post data using your two code snippets, I see some differences in the requests.
Here is the raw post for the first code sample (that you say does not work):
POST http://testing.foo.com/api/Values HTTP/1.1
Host: testing.foo.com
Expect: 100-continue
Connection: Keep-Alive
Content-Length: 75
{
id:"1",
title:"title text",
post:"post text",
isDeleted:"False"
}
This is the raw post for the code in your update (code that you say works):
POST http://testing.foo.com/api/Values HTTP/1.1
Content-Type: application/json
Host: testing.foo.com
Content-Length: 75
Expect: 100-continue
{
id:"2",
title:"title text",
post:"post text",
isDeleted:"False"
}
The differences in the two requests are as follows:
In the first request, the content type is never set.
In the first request, the content is UTF8 encoded.
To fix your non-working code, I would suggest you try one or both of the following:
Set the content type to application/json
Not UTF8 encode the request
At that moment this solution is most useful.
public static async Task<string> LoadData(string json, string serverUrl)
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(Constants.LocalServer));
request.ContentType = "application/json";
request.Method = "POST";
using (var requestStream = await request.GetRequestStreamAsync())
{
var writer = new StreamWriter(requestStream);
writer.Write(json);
writer.Flush();
}
using (var resp = await request.GetResponseAsync())
{
using (var responseStream = resp.GetResponseStream())
{
var reader = new StreamReader(responseStream);
return = reader.ReadToEnd();
}
}
}