How to switch from HttpWebRequest to HttpClient? - c#

I'm trying to send a request through HttpClient and read a response. This is the curl from which I tried to do this:
curl -H "Content-Type: application/json" --data \
'{comment: {text: "vulgar content"},
languages: ["en"],
requestedAttributes: {TOXICITY:{}} }' \
https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=YOUR_KEY_HERE
I've tried something likes this:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=YOUR_KEY_HERE"))
{
request.Content = new StringContent("{comment: {text: \"vulgar\"},\n languages: [\"en\"],\n requestedAttributes: {TOXICITY:{}} }");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
using var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
}
And this:
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Content-Type", "text/plain");
HttpContent postData = new StringContent("{comment: {text: \"what kind of idiot name is foo?\"},\n languages: [\"en\"],\n requestedAttributes: {TOXICITY:{}} }");
HttpResponseMessage response = await client.PostAsync("https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=AIzaSyCZdLeFtJhbqD9_WJ2Q4UiDB-THRzQhp5g", postData);
if (response.IsSuccessStatusCode)
{
var x = await response.Content.ReadAsStringAsync();
}
else
{
//Do something when request fails
return true;
}
}
However both of those snippets just break on the response part. No exception, no communicates, console says programe ends with code 0. But sending it via HttpWebRequest works just fine:
var url = "https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=YOUR_KEY_HERE";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/json";
var data = #"{comment: { text: ""what kind of idiot name is foo?""},languages: [""en""], requestedAttributes: {TOXICITY:{}} }";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Console.WriteLine(httpResponse.StatusCode);
My question is, what am I doing wrong in sending it through HttpClient? I'm replacing YOUR_KEY_HERE with my API key.

Okay, so following Jon Skeet advice on providing reproducable example, I noticed that my Task wasn't marked as async. So I solved it by making a request in async Task method:
public async Task<string> FirstSnippet()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=AIzaSyCZdLeFtJhbqD9_WJ2Q4UiDB-THRzQhp5g"))
{
request.Content = new StringContent("{comment: {text: \"vulgar\"},\n languages: [\"en\"],\n requestedAttributes: {TOXICITY:{}} }");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
using var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
return body;
}
}
}
And calling method in Main:
Program p = new();
Console.WriteLine(await p.FirstSnippet());

Related

POST Request with json in c#

I am attempting to do a POST request which I have got working through Postman but I am getting a 400 error when done from code.
I am trying to reach the POST endpoint from here: http://developer.oanda.com/rest-live-v20/order-ep/
Here is my code, does anything look incorrect or have I missed anything?
public void MakeOrder(string UID)
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer 11699873cb44ea6260ca3aa42d2898ac-2896712134c5924a25af3525d3bea9b0");
client.Headers.Add("Content-Type", "application/json");
client.UploadString(url, body);
}
}
I'm very new to coding so apologies if it is something very simple.
use HttpClient from System.Net.Http:
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body , Encoding.UTF8, "application/json");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}
I would suggest you to use HttpClient over WebClient. You can find here the difference.
using (var httpClient = new HttpClient())
{
string url = $"https://api-fxpractice.oanda.com/v3/accounts/{UID}/orders";
string body = "{'order': {'units': '10000', 'instrument': 'EUR_USD', 'timeInForce': 'FOK', 'type': 'MARKET', 'positionFill': 'DEFAULT'}}";
var content = new StringContent(body, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTIzMDY0NTQsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ.c-3boD5NtOEhXNUnzPHGD4rY1lbEd-pjfn7C6kDPbxw");
var result = httpClient.PostAsync(url, content).Result;
var contents = result.Content.ReadAsStringAsync();
}

How to pass request content with HttpClient GetAsync method in c#

How do I pass request content in the HttpClient.GetAsync method? I need to fetch data depending upon request content.
[HttpGet]
public async Task<HttpResponseMessage> QuickSearch()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch");
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
If you are using .NET Core, the standard HttpClient can do this out-of-the-box. For example, to send a GET request with a JSON body:
HttpClient client = ...
...
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("some url"),
Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
If you want to send content, then you need to send it as query string (According to your API route)
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch/paramname=<dynamicName>&paramValue=<dynamicValue>");
And in API check for "paramName" and "paramValue"
this works for me:
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("your url"),
Content = new StringContent("your json", Encoding.UTF8, ContentType.Json),
};
using (var response = await httpClient.SendAsync(request))
{
string apiResponse = await response.Content.ReadAsStringAsync();
}
}
EDITED:
This is minor different then #SonaliJain answer above:
MediaTypeNames.Application.Json instead of ContentType.Json
I'm assuming that your "request content" would be POST data, no?
If you're sending it using the standard form content way of doing it, you would first have to build the content:
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", "theperplexedone"),
new KeyValuePair<string, string>("password", "mypassword123"),
});
And then submit it using PostAsync instead:
var response = await client.PostAsync("http://localhost:8080/document/quicksearch", content);
Hi all thank you for your comments, i got the solution
[HttpGet]
public async Task<HttpResponseMessage> QuickSearch(HttpRequestMessage Query)
{
Debugger.Launch();
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
Console.WriteLine(Query);
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/document/quicksearch/"+ Query.RequestUri.Query);
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
{
Console.Write("Failure");
}
return response;
}
}
catch (Exception e)
{
throw e;
}

POST Request UWP

I writing UWP app.
I need to send POST request with json to server
Here is my code for downloading JSON and writing to value:
public async void AllOrders_down()
{
string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";
var json = await FetchAsync(url);
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);
OrdersList = new List<RootObject>(rootObjectData);
}
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
How I need to send POST request with this json to server?
Thank's for help.
Here is an example Post request that I have used in a UWP application.
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(#"http://test.com/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
string endpoint = #"/api/testendpoint";
try
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(yourPocoHere), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
//do something with json response here
}
}
catch (Exception)
{
//Could not connect to server
//Use more specific exception handling, this is just an example
}
}
You should be using httpClient.PostAsync().

POST request in UWP not sending

I writing app for UWP
I receive json from back end like this:
string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
I try to send POST request like this
OrdersList = new List<RootObject>(rootObjectData);
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(#"http://api.simplegames.com.ua");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
string endpoint = #"/post_from_local.php";
try
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(OrdersList), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
Debug.WriteLine(jsonResponse);
//do something with json response here
}
}
catch (Exception)
{
//Could not connect to server
//Use more specific exception handling, this is just an example
}
}
But, Back end dev said that he see empty row, but data is not received.
Thank's for help. Where is my error?
Change this line:
var stream = await httpClient.GetStreamAsync(url);
to:
var stream = httpClient.GetStreamAsync(url).Result;

VSO REST API Create work item error 404

I'm trying to create a work item with this code :
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0");
httpWebRequest.ContentType = "application/json-patch+json";
httpWebRequest.Credentials = new NetworkCredential("me",Settings.Default.token);
httpWebRequest.Method = "PATCH";
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
op="add",
path= "/fields/System.Title",
value="New bug from application"
});
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
HttpWebResponse httpResponse = null;
try { httpResponse = (HttpWebResponse) httpWebRequest.GetResponse(); }
catch (WebException e)
{
//Exception catched there, error 404
Console.WriteLine(e.Status); //Writes ProtocolError
throw;
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
But I get an error 404 (Not Found).
When i change the method(to PUT or POST) I get a code for a visual studio page.
When i'm going to https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0 i can see some json. So this is not an URL error.
I finally can do what I want :
public async Task CreateBug(Bug bug)
{
string token = Settings.Default.token;
string requestUrl = "https://xxx.visualstudio.com/defaultcollection/xxx/_apis/wit/workitems/$Bug?api-version=1.0";
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = this.GetProxy(),
UseProxy = true,
UseDefaultCredentials = true
};
HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "me", token))));
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, requestUrl)
{
Content = new StringContent(GetStrJsonData(), Encoding.UTF8,
"application/json-patch+json")
};
HttpResponseMessage hrm = await httpClient.SendAsync(request);
Response = hrm.Content;
}
I've used an HttpClient instead of an HttpWebRequest

Categories

Resources