I am passing parameters and receiving a lot of values back from my webservices one of these values is a string that was suposed to be "Açougue" but im getting something different from that something like "A┌ougue". What can i do to make my app to be able to set that word right?
var request2 = new RestRequest (String.Format("?param1={0}¶m2={1}", (int)CGI_FUNC.GETSERVICOS, classGlobalVars.usuario));
asyncHandle = client.ExecuteAsync (request2, response => {
servicoLista = new List<objectServico> ();
Console.WriteLine("Something: "+response.ContentEncoding);
if (response.Content != "") {
}
});
So tried changing my response.ContentEncoding to "utf-8" or something but it didnt worked.
Thanks for all the help. ^^
try this:
var request2 = new RestRequest ();
request2.AddParameter("text/xml; charset=utf-8", String.Format("?param1={0}¶m2={1}", (int)CGI_FUNC.GETSERVICOS, classGlobalVars.usuario), ParameterType.RequestBody);
asyncHandle = client.ExecuteAsync (request2, response => {
servicoLista = new List<objectServico> ();
Console.WriteLine("Something: "+response.ContentEncoding);
if (response.Content != "") {
}
});;
Related
I've been trying to simply call an api on an android build supporting 64 bit (IL2CPP build) and the UnityWebRequest class didnt seem to work. It's being called via a simple ui button click. It hits the webRequest.SendWebRequest(); and nothing happens. Ive tried the following samples. One, directly from the Unity docs for UnityWebRequest and others using standard HttpClient.
UnityWebRequest:
IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
webRequest.SetRequestHeader("Authorization", "Bearer " + API_KEY);
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
debugText.text = ": Error: " + webRequest.error;
coroutineAllowed = false;
}
else
{
debugText.text = ":\nReceived: " + webRequest.downloadHandler.text;
dynamic jsonObj = JsonConvert.DeserializeObject(webRequest.downloadHandler.text);
foreach (var obj in jsonObj["businesses"])
{
businessResults.Add(new Business()
{
name = (string)obj["name"],
image_url = (string)obj["image_url"],
review_count = (string)obj["review_count"],
rating = (string)obj["rating"],
Coordinates = new Coordinates()
{
Latitude = (float)obj["coordinates"]["latitude"],
Longitude = (float)obj["coordinates"]["longitude"]
},
price = (string)obj["price"]
});
}
debugText.text = businessResults.Count.ToString();
//coroutineAllowed = true;
}
debugText.text = "getRequest 4";
}
}
This unfortunately did nothing at the yield return webRequest.SendWebRequest();
The next sample I tried was using HttpClient():
IEnumerator HttpClientCall(string uri) //possibly wrap in IEnumerator
{
debugText.text += "http coroutine started" +Environment.NewLine;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY);
var response = httpClient.GetAsync(uri);
if (response.Result.StatusCode != HttpStatusCode.OK)
{
debugText.text += "FAILED HTTP GET";
}
yield return response.Result.Content.ReadAsStringAsync();
dynamic jsonObj = JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result);
foreach (var obj in jsonObj["businesses"])
{
businessResults.Add(new Business()
{
name = (string)obj["name"],
image_url = (string)obj["image_url"],
review_count = (string)obj["review_count"],
rating = (string)obj["rating"],
Coordinates = new Coordinates()
{
Latitude = (float)obj["coordinates"]["latitude"],
Longitude = (float)obj["coordinates"]["longitude"]
},
price = (string)obj["price"]
});
debugText.text += Environment.NewLine + ((string)obj["name"]);
}
}
}
Once again, nothing when it hits yield return response.Result.Content.ReadAsStringAsync();
These all work on PC, and they both return results that i'm expecting.
The next thing i heard was about setting the android manifest application tag with android:usesCleartextTraffic="true"
This unfortunately, also did nothing for me lol. I know it has to be the 64 support, because this works on a standard build. The moment i go to build with 64 support, it doesnt work.
Any help on why it's not returning appropriately would be very helpful.
side note, i know the code is pretty ugly, but after i can figure out why the build doesnt work on the device a heavy refactoring is going to be in play. Thanks in advance!
So after a lot of trouble shooting ive found out why this was not working. The main issue seems to be stemming from my use of the standard Newtonsoft Json package when Unity, apparently, has their own internal JsonUtility class. After changing this:
dynamic jsonObj = JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result);
To This:
var js = JsonUtility.FromJson<T>(response.Result.Content.ReadAsStringAsync().Result);
my results are finally showing in the the apk build correctly.
Also, to note that to map correctly, the JsonUtility.FromJson must be typed to a class that exactly mirrors the incoming json object explicitly.
The page article that finally helped me with this issue is here.
P.S.
Thank you to #RetiredNinja for trying to help instead of just downvoting and saying nothing of value. You're amazing!
I have a problem with my custom Dialog.
I want to show it while my application do something (in particular, creates a bitmap and does a HTTP request).
This is the portion of my code:
LoadingDialog myLoading = new LoadingDialog();
myLoading.Show()
TakePicture();
while (myPhotoFace == null) { }
Context context = Android.App.Application.Context;
if (Connectivity.isConnected(context))
{
byte[] bytePhoto;
using (var stream = new MemoryStream())
{
Constants.myGallery.Compress(Bitmap.CompressFormat.Jpeg, 40, stream);
bytePhoto = stream.ToArray();
}
byte[] byteFace;
using (var stream = new MemoryStream())
{
myPhotoFace.Compress(Bitmap.CompressFormat.Jpeg, 40, stream);
byteFace = stream.ToArray();
}
MediaEmotion myMedia = new MediaEmotion();
string token = Utils.utils.GetParametro("token");
myMedia.mediaID = 0;
myMedia.face = byteFace;
myMedia.photo = bytePhoto;
var client = new RestClient("https://myServer.net/");
var request = new RestRequest("/Controller/Method?token=" + token, Method.POST);
string json = JsonConvert.SerializeObject(myMedia);
request.AddParameter("stringaMediaEmotion", json);
IRestResponse response = client.Execute(request);
Object myObject = JsonConvert.DeserializeObject<Object>(response.Content.ToString());
[...]
After, I do something before start new activity.
As you can see, as a first operation I show my dialog (which, I verified, works correctly) but only appears as the last thing before moving on to the new activity. Also by simply trying to change the text of a textview the problem is the same.
Why? What is the problem? How can resolve this?
Try to put all the network related code inside an async task: you'll free the main thread from network operation and the popup will appear until you'll move to another activity.
You can find some good examples and documentation here https://blog.xamarin.com/getting-started-with-async-await/
I've created in Xamarin Forms for iOS a HttpClient function to send a picture from the device to my server. The core function is
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fName
};
fileContent.Headers.ContentDisposition.Parameters
.Add(new NameValueHeaderValue("userId", UserId.ToString()));
content.Add(fileContent);
using (var client = new HttpClient()) {
client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
// more code
}
}
I'm using System.Net.Http. I tried to use the same function for a project in Android but surprisingly it doesn't work. The problem is in the header: if I inspect fileContent I can see every keys but for webapi on the server FileName is not received.
After some logs, I changed this function adding more client.DefaultRequestHeaders like
client.DefaultRequestHeaders.Add("FileName", fName);
Now the webapi receives FileName param.
Now my question is: what did I wrong?
Personally, I use the Add method on MultipartFormDataContent that accepts a filename.
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
...
// Use the overload Add method which accepts a file name
content.Add(fileContent, "FileName", fName);
...
I'm not sure if this will solve your problem or not, but it works for me.
I am working on a project where I need to download a javascript and use it to calculate some values. This is already working on iOS so the javascript seems to be just fine.
Here is the stripped down javascript (I have removed the content as I do not own the script):
var resultArray = [];
function calculateRemainingAmountForForecastWeeks(numberOfWeeks, weeklyDisposable, easing, safetyZone, safetyZoneEasing, overSpentThisWeek) {
// Some calculations...
resultArray[numberOfWeeks] = spentBeyondForecast;
}
I am using Rhino and here is what I do:
org.mozilla.javascript.Context rhino = org.mozilla.javascript.Context.enter();
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
rhino.evaluateString(scope, WeeklyApplication.getCalculatorJS(), "JavaScript", 0, null);
Object obj = scope.get("calculateRemainingAmountForForecastWeeks", scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object[] params = new Object[]{numberOfWeeks, weeklyDisposable, easing, safetyZone, safetyZoneEasing, overSpentThisWeek};
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = org.mozilla.javascript.Context.toString(jsResult);
Log.d(TAG, "SKN-calculate3=" + result);
}
} finally {
org.mozilla.javascript.Context.exit();
}
I know it is not the most optimized use of scope here, but I just need to get it working first. I keep getting "undefined" in the result String, what am I doing wrong here?
And when I do get this working, how do I then get the values stored in the "resultArray"?
Thank you
Søren
From code that you posted, it looks like function calculateRemainingAmountForForecastWeeks() doesn't return anything, so it's ok to get Undefined from it.
Getting value from resultArray is easy, as it's just a field in your scope scriptable object:
Object[] params = new Object[]{numberOfWeeks, weeklyDisposable, easing, safetyZone, safetyZoneEasing, overSpentThisWeek};
// function doesn't return anything
jsFunction.call(rhino, scope, scope, params);
NativeArray resultArray = (NativeArray) scope.get("resultArray", scope);
double result = ((Number) resultArray.get(numberOfWeeks)).getDoubleValue();
Log.d(TAG, "SKN-calculate3=" + result);
Note: of course, I don't know what your types are, so probably you'd have to update this snippet to make it work for you.
How to display JSON coming from php in intel App Framwork app. I have tried .getJSON() and .getJSONP() methods. Is there any full guide explaining these methods and how to use them?
Here are documentations for $.getJSON() and $.jsonP()
found the answer .
function getRaceData() {
var postBody = "";
postBody = "rid="+theRID;
var parameters = new AppMobi.Device.RemoteDataParameters();
parameters.url = "http://MyWebSite.com/php_src/getRaceData.php";
parameters.id = "1007";
parameters.method = "POST";
parameters.body = postBody;
jq.ui.showMask('loading race data');
AppMobi.device.getRemoteDataExt(parameters);
}
//then somewhere in your event handler, check the ID of the response and process the JSON....
case 1007: //got race data
var raceData = jq.parseJSON(event.response);
jq("#raceRCList").hide();
jq("#raceRCname").html(raceData.race_name);
jq("#raceRCdate").val(raceData.date);
jq("#raceRCstart").val(raceData.start_time);
jq("#raceRCData").show();
break;