How do you send a json object to php backend properly - c#

While using something like this
"
Dictionary<string, string> form = new Dictionary<string, string>
{
{_metajson, JsonConvert.SerializeObject(metaJson)}
};
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(form));
However on the php side of things with $_Request I get the string and all the quotes are turned into " so the json looks like
{"name":"myname"}
Is there a better way to send json to a php backend?
On the PHP end of things I am simply assigning the json which has now lost the quotes and has weird marks with
$json = $_REQUEST["test"];
The json I am sending is in memory, its not saved to a file anywhere. It is very small like shown above and is needed for the purposes of the application I am writing.

Use php://input
php://input is a read-only stream that allows you to read raw data from the request body.
Example:
$json_string = file_get_contents('php://input');
//Converting It to PHP object:
$data = json_decode($json_string );

I was just working with the same problem and here is my solution, it works for me
$data = $_POST['json'] ;
$json = json_decode($data, true);
echo json_encode($json);
afterwards, you can take the $json variable an do whatever you want to do with it

I ended up changing the approach which worked very well
I simply base64 encoded the json to avoid http changing special characters to odd string formats like " to " and what not.
C# side - using this string in the dictionary form
string encodedJson = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metaJson)));
PHP side
$encoded_input = $_REQUEST["metajson"];
$base64_decoded_input = base64_decode($encoded_input, true);
if (!$base64_decoded_input)
{
// error out
}
$meta_json = json_encode(json_decode($base64_decoded_input));

Related

Sending tokens to Actions On Google returns error "Can't parse the response. The response needs to be JSON format"

Good morning,
I am using ASP.NET HTTP API as Actions on Google fullfilment. I have an error message when I try to send tokens to Actions on Google project. Regarding to another question I read I made sure to have clear int value (not decimal) and it doesn't work.
My JSON which I send to Actions on Google:
{"token_type":"Bearer","access_token":"edeaa27e-12b7-43a1-bc7c-e6bbf9af71c3","refresh_token":"4344383b-cf07-4d12-a5c2-44b6481f5f48","expires_in":86400}
Error message:
{
insertId: "1o7lj2bmu"
jsonPayload: {
#type: "type.googleapis.com/google.identity.accountlinking.type.AccountLinkingError"
errorReason: "Can't parse the response. The response needs to be JSON format."
response: {
body: ""{\"token_type\":\"Bearer\",\"access_token\":\"edeaa27e-12b7-43a1-bc7c-e6bbf9af71c3\",\"refresh_token\":\"4344383b-cf07-4d12-a5c2-44b6481f5f48\",\"expires_in\":86400}""
status: 200
}
step: "AUTH_CODE_EXCHANGE"
}
logName: "projects/smartlightproject-f47f4/logs/accountlinking-pa.googleapis.com%2Ferror"
receiveTimestamp: "2022-07-12T12:32:40.739532642Z"
resource: {2}
severity: "ERROR"
timestamp: "2022-07-12T12:32:40.539Z"
}
What's wrong with that JSON? Or maybe I should do it in some other way?
I will be very very grateful if you could help me with that.
Here's my code after some improvements:
var result_acceess_token = "edeaa27e-12b7-43a1-bc7c-e6bbf9af71c3";
var result_refresh_token = "4344383b-cf07-4d12-a5c2-44b6481f5f48";
var expires_expires_in = 86400;
var resultObj = new
{
token_type = "Bearer",
access_token = result_acceess_token,
refresh_token = result_refresh_token,
expires_in = expires_expires_in
};
return Ok(resultObj);
Earlier I tried to serialize JSON with JsonConvert and return it as JsonResult or raw string value.
It looks like the response you're sending back is the JSON as a quoted string. That is - there is a quote at the beginning and end of the JSON. While this is a valid JSON string (it is, after all, a quoted string), it sounds like it is looking for a JSON object.
Verify the body of the response and make sure it does not contain the opening and closing quotes.

How can i search a hebrew word from a website using c#

Im trying to search a Hebrew word in a website using c# but i cant figure it out.
this is my current state code that im trying to work with:
var client = new WebClient();
Encoding encoding = Encoding.GetEncoding(1255);
var text = client.DownloadString("http://shchakim.iscool.co.il/default.aspx");
if (text.Contains("ביטול"))
{
MessageBox.Show("idk");
}
thanks for any help :)
The problem seems to be that WebClient is not using the right encoding when converting the response into a string, you must set the WebClient.Encoding property to the expected encoding from the server for this conversion to happen correctly.
I inspected the response from the server and it's encoded using utf-8, the updated code below reflects this change:
using (var client = new WebClient())
{
client.Encoding = System.Text.Encoding.UTF8;
var text = client.DownloadString("http://shchakim.iscool.co.il/default.aspx");
// The response from the server doesn't contains the word ביטול, therefore, for demo purposes I changed it for שוחרות which is present in the response.
if (text.Contains("שוחרות"))
{
MessageBox.Show("idk");
}
}
Here you can find more information about the WebClient.Encoding property:
https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.encoding?view=netframework-4.7.2
Hope this helps.

C# eBay API Upload Return Label

I haven't been able to figure out how to properly upload a label onto eBay using the /post-order/v2/return/{returnId}/file/upload call. I keep getting "The remote server returned an error: (400) Bad Request.".
I believe it may have to do with the image encoding, but I am not entirely certain. I was already able to approve the return with POST /return/{returnId}/decide but the next step in uploading is the problem. I have the image data saved as a base 64 string in a database. I know the data is good, because in other calls I am able to transform that base 64 string into an image in my application. So the data from the image isn't in question. The thing is on http://developer.ebay.com/Devzone/post-order/post-order_v2_return-returnId_file_upload__post.html#samplesellerlabel it states that the image data should be "base64-encoded binary representation of the file".
So is it possible that the data I received when grabbing the image with Convert.ToBase64String(imageBytes) is not what I actually need? There are little to no examples on how to do this particular call in C# and I've tried so many things. I've checked the JSON syntax and it looks to be correct. (I've removed a large portion of the string as it is too large.)
{"fileName":"5074119065_shippingLabel.jpeg","data":"R0lGODlhCAewBIEAAAAAAP///wAAAAAAACH/C05...zR2On54kkB4nfJYrLFRAAOw==","filePurpose":"LABEL_RELATED"}
I'm fairly convinced that the image data is somehow not formatted correctly, but I'm just not sure. If anyone has any experience with this call I'd appreciate your help. Below is my code and the error comes up on the last line. The headers and the JSON code has worked without any issues on other eBay calls which is also a reason I suspect my problem may have to do with the formatting of the image data.
string url = "https://api.ebay.com/post-order/v2/return/" + returnId + "/file/upload";
var cancelOrderRequest = (HttpWebRequest)WebRequest.Create(url);
cancelOrderRequest.Headers.Add("Authorization", "TOKEN " + authToken);
cancelOrderRequest.ContentType = "application/json";
cancelOrderRequest.Accept = "application/json";
cancelOrderRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");
cancelOrderRequest.Method = "POST";
string fileName = returnId + "_shippingLabel.jpeg";
using (var streamWriter = new StreamWriter(cancelOrderRequest.GetRequestStream()))
{
string json = "{\"fileName\":\"" + fileName + "\",\"data\":\"" + labelData + "\",\"filePurpose\":\"LABEL_RELATED" + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var response = (HttpWebResponse)cancelOrderRequest.GetResponse();
Hmm. The eBay documentation appears to be inconsistent. In the top part of the documentation page you linked for the Upload Return File method call, it seems to indicate that the data part of the JSON should be an array of strings, not just a single string.
Payload model
The following lists all fields that could be included in the request.
{ /* UploadFileRequest */
"data": [
string
/* More string nodes here */
],
"fileName": string,
"filePurpose": token
}
But in the JSON sample they show on the same page, the data is clearly a single string like you have it in your code. (Notice the square brackets are missing.)
URL format. See also the non-wrapped version of this URL.
POST https://api.ebay.com/post-order/v2/return/5000124931/file/upload
{
"fileName" : "jasmine.jpeg",
"data" : "SGVyZSBpcyB5b3VyIHJld...YWNraW5nIG51bWJlciBpcyAxMjM0NTY3ODk4NzY1",
"filePurpose" : "ITEM_RELATED"
}
I would try changing it to an array to match the documented payload. I'm guessing the sample is probably wrong here.
Also, I would highly recommend using a JSON serializer like Json.Net rather than hand-rolling your own JSON, as it is very easy to get the formatting wrong, which will just end up giving you more "400 Bad Request" headaches. Instead, try making the JSON by using an anonymous object and then serializing it, like this:
var payload = new
{
fileName = returnId + "_shippingLabel.jpeg",
data = new List<string> { labelData },
filePurpose = "LABEL_RELATED"
};
string json = JsonConvert.SerializeObject(payload);

DownloadString and Special Characters

I am trying to find the index of Mauricio in a string that is downloaded from a website using webclient and download string. However, on the website it contains a foreign character, Maurício. So I found elsewhere some code
string ToASCII(string s)
{
return String.Join("",
s.Normalize(NormalizationForm.FormD)
.Where(c => char.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark));
}
that converts foreign characters. I have tested the code and it works. So the problem I have is that when I download the string, it downloads as MaurA-cio. I have tried both
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
Neither stop it from downloading as MaurA-cio.
(Also, I cannot change the search as I am getting the search term from a list).
What else can I try?
Thanks
var client = new WebClient { Encoding = System.Text.Encoding.UTF8 };
var json = client.DownloadString(url);
this one will work for any character
DownloadString doesn't look at HTTP response headers. It uses the previously set WebClient.Encoding property. If you have to use it, get the headers first:
// call twice
// (or to just do a HEAD, see http://stackoverflow.com/questions/3268926/head-with-webclient)
webClient.DownloadString("http://en.wikipedia.org/wiki/Maurício");
var contentType = webClient.ResponseHeaders["Content-Type"];
var charset = Regex.Match(contentType,"charset=([^;]+)").Groups[1].Value;
webClient.Encoding = Encoding.GetEncoding(charset);
var s = webClient.DownloadString("http://en.wikipedia.org/wiki/Maurício");
BTW--Unicode doesn't define "foreign" characters. From Maurício's perspective, "Mauricio" would be the foreign spelling of his name.

Reading from JSON, data not displayed

I'm having this strange problem when i try to access elements in json from javascript. i retreve a json string from a url like so,
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"www.someurl.com");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
sjson = client.DownloadString(#"www.someurl.com");
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = Int32.MaxValue;
sjson = oSerializer.Serialize(sjson);
But when i access this sjson variable from javascript in html code, it doesn't return anything, but if i hard code it, it returns the values, please help on this one. I tried many things but didn't work. I also tried to just pass the retreieved json string without serializing, when i do that the javascript stops working. :( following is the javascript code,
<script type="text/javascript">
var jsons = JSON.parse('<%=sjson%>');
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>
The issue is
document.writeln(myobject.Body[0].RowId.SensorIdValue);
returns a value if i use the myobject variable, but
document.writeln(jsons.Body[0].RowId.SensorIdValue);
returns nothing when i use it with the parsed value. :(
following is the sample of the json output (response.write) i get after running the serializer via c#,
Please help me on this one..i cant seem to find the problem here.
EDIT:
if it help, the fiollowing is the json string i get straight from the server witout making any serializations,
Few contents of the question have been removed due to owner request
What you're seeing there is doubly JSON-serialized data. You retrieved JSON from the remote server and then JSON encoded it a second time with JavaScriptSerializer. This is a post I wrote about that, in the context of ASMX ScriptServices, which explains in more detail: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/. Your case isn't exactly the same, but the end result is.
Remove the JavaScriptSerializer code and return the JSON string you retrieved (sjson) instead of serializing it a second time.
You don't need to use a Json serializer because the remote server already returns a JSON encoded string that you could directly use in your page and avoid the double encoding.
So:
public string GetJson()
{
// Create Client
using (WebClient client = new WebClient())
{
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
return client.DownloadString(
#"www.someurl.com"
);
}
}
and then:
<script type="text/javascript">
var jsons = <%= GetJson() %>;
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>

Categories

Resources