Passing symbols inside Json through HttpWebRequest - c#

I try to pass message to MS Flow in Json format, using following method, but once I pass any symbols (like ") I get an error as symbols are recognized as code.
public static bool notification(string customer, string comment)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("my msflow link goes here");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"customer\":\"" + customer + "\",\"comment\":\"" + comment + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
return true;
}
catch (Exception)
{
return false;
}
}

Try to use the JSON.NET to serialize your objekt in the code like this:
string json = JsonConvert.SerializeObject(<your object>);

Related

Hololens app gets stuck when I try to upload an audio file via HttpWebRequest

private void Upload(){
string apiURL = Globals.GoogleSpeechToTextURL + Globals.GoogleSpeechToTextApiKey;
string Response;
Debug.Log("Uploading " + filePath);
var fileInfo = new System.IO.FileInfo(filePath);
Debug.Log("Size: "+fileInfo.Length);
gtext.text = fileInfo.Length + " ";
Response = HttpUploadFile(apiURL, filePath, "file", "audio/wav; rate=44100");
var list = new List<Event>();
JObject obj = JObject.Parse(Response);
//return event array
var token = (JArray)obj.SelectToken("results");
if (token != null)
{
foreach (var item in token)
{
string json = JsonConvert.SerializeObject(item.SelectToken("alternatives")[0]);
list.Add(JsonConvert.DeserializeObject<Event>(json));
}
Debug.Log("Response String: " + list[0].transcript);
}
}
public string HttpUploadFile(string url, string file, string paramName, string contentType)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
Debug.Log(string.Format("Uploading {0} to {1}", file, url));
Byte[] bytes = File.ReadAllBytes(file);
String file64 = Convert.ToBase64String(bytes,
Base64FormattingOptions.None);
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"config\": { \"languageCode\" : \"en-US\" }, \"audio\" : { \"content\" : \"" + file64 + "\"}}";
// Debug.Log(json);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
// Debug.Log(httpResponse);
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
catch (WebException ex)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
// Debug.Log(resp);
}
return "empty";
}
This is the code I am using to upload an audio file. When HttpUploadFile gets called, the app pauses and shows a black screen for a second and then continues. I tried calling Upload function through coroutine, and also tried this Use Unity API from another Thread or call a function in the main Thread. But still it pauses while uploading. The file size is around 200 KB
What else can I try to avoid this problem?
Use UnityWebRequest instead. You cannot make blocking HTTP request calls on the main thread.
Also, the HTTP API has a pattern for file uploads, packing an audio file into a base 64-encoded field in JSON is going to crash your JSON parser if the string is too large.

How to Return the HTTP Call Response in C#

I am trying to return the response of productRating in this HTTP call. I have tried several ways but haven't been successful. Any idea? The response is a json with an object that I want to get access to the streamInfo>avgRatings>_overall
public double GetRatings(string productId)
{
const string URL = "https://comments.au1.gigya.com/comments.getStreamInfo";
var apiKey = "3_rktwTlLYzPlqkzS62-OxNjRDx8jYs-kV40k822YlHfEx5VCu93fpUo8JtaKDm_i-";
var categoryId = "product-ratings";
var urlParams = "?apiKey=" + apiKey + "&categoryID=" + categoryId + "&streamID=" + productId + "";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);
var productrating = (response["streamInfo"]["avgRatings"]["_overall"]);
return;
}
GetRatings Erroe: not all code paths return a value.
Productrating Error:can not apply indexing with [] to an expression of type HttpResponseMessage
return Error: an object of a type convertable to double is required
ApiCall has to return something. Looking at the example below.
#functions {
public static string ApiCall()
{
return "Hello World!";
}
}
#{
var ratings = ApiCall();
}
#if (ratings != null)
{
<div class="gig-rating-stars" content=#ratings></div>
}
I am using this function for POST API Call and it returns response string and if you want to add security features you can send it in JObject because its the secure channel to send Jobject as a parameter on URL
## Code Start ##
protected string RemoteApiCallPOST(JObject elements, string url)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
// JObject jsonResult = new JObject();
string id;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(elements);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
id = (streamReader.ReadToEnd()).ToString();
return id;
}
}
catch (Exception EX)
{
return "";
}
}
Code End
The only change I needed to do is changing "var" to "dynamic" in :
dynamic response = JsonConvert.DeserializeObject(client.GetAsync(urlParams).Result.Content.ReadAsStringAsync().Result);

Get the HTML result even if we get an exception with this code

I would like to return the HTML result of a page with this code below, even if I get a 403 response code for example, so if it throw an exception.
This is the current code I have, and as you can see I would like to return the HTML result of the page when an exception is throwed too.
public string authenticate(string user, string pass)
{
try
{
var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
request.ContentType = "application/json";
request.Method = "POST";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"agent\":{\"name\":\"Minecraft\",\"version\":1},\"username\":\"" + user + "\",\"password\":\"" + pass + "\",\"clientToken\":\"6c9d237d-8fbf-44ef-b46b-0b8a854bf391\"}";
writer.Write(json);
writer.Flush();
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd(); // the html result
}
}
}
catch (Exception)
{
return "the html result";
}
}
Thanks for help.

Paypal saved card rest API through 400 Bad Request error in C#

I am developing application using .net MVC C#. I tried to call rest API of PayPal for save credit card details, my code were working fine but suddenly it starting through 400 Bad Request exception. here is my code,
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/vault/credit-card");
var result = "";
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var loginjson = new JavaScriptSerializer().Serialize(new
{
payer_id = cardDetails.PayerId.Trim(),
type = cardDetails.CardType.Trim(),
number = cardDetails.CardNumber.Trim(),
expire_month = cardDetails.ExpireMonth.Trim(),
expire_year = cardDetails.ExpireYear.Trim(),
first_name = cardDetails.FirstName.Trim()
});
streamWriter.Write(loginjson);
streamWriter.Flush();
streamWriter.Close();
//The code fails when creating the Response here, and go into catch block
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
catch (Exception ex)
{
return ex.GetBaseException().Message;
}
}
}
Can anyone help me out from this error?
Thank you in advance.
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
//my stuff
}
catch (WebException ex)
{
string text = null;
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
return text; //ex.GetBaseException().Message;
}
}
This is changed I have done in my catch block to trace proper error, so it return me that error which I was facing.

How do I send a json array to an ASP.NET server?

I wrote this code to send some JSON to a server:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.brilliantit.ir/getDetail.aspx");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//string json = "{\"id\":\"ahbarres\"}";
string json = "{\"id\":\""+label1.Text+"\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
String temp = "";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
temp = result.ToString();
}
But, I want to send a JSON array to a server. How can I do this?

Categories

Resources