Web service not working in web player build Unity5 - c#

I am trying to get product description from server using web service. This is working fine in unity editor but when i created web player build it's not working.
what should be the problem ? Why it is not working in web player build ?
this is the sample code i am trying :
public void product_detail()
{
string url = "http://*****/api.php?method=get_product_detail&product_id=" + name + "";
Debug.Log(url);
WWW www = new WWW(url);
StartCoroutine(WaitForRequest1(www));
}
IEnumerator WaitForRequest1(WWW www)
{
yield return www;
// check for errors.
if (www.error == null)
{
Debug.Log("WWW data: " + www.data);
Processjson(www.data);
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
private void Processjson(string jsonString)
{
JsonData jsonvale = JsonMapper.ToObject(jsonString);
var vc = JsonConvert.DeserializeObject(jsonString,typeof(Rootobject)) as Rootobject;
//string status = jsonString;
p_deail = jsonvale["detail"].ToString();
p_price = jsonvale["price"].ToString();
PlayerPrefs.SetString ("P_detail",p_deail);
PlayerPrefs.SetString ("P1_price",p_price);
Component com = GameObject.Find("FPSController").GetComponent("FirstPersonController") as MonoBehaviour;
(com as MonoBehaviour).enabled = false;
PlayerPrefs.SetString("Product",prefab.name.ToString());
GUIWindow.SetActive(true);
GameObject clone = Instantiate (prefab, Vector3.zero, Quaternion.identity) as GameObject;
clone.AddComponent<zoomC>();
clone.AddComponent<rotatC>();
clone.transform.position = Camera.main.transform.position + Camera.main.transform.forward*1.0f + Camera.main.transform.right*-0.5f + Camera.main.transform.up*-0.2f;
clone.transform.rotation = new Quaternion( Camera.main.transform.rotation.x, Camera.main.transform.rotation.y, Camera.main.transform.rotation.z, Camera.main.transform.rotation.w );
clone.transform.localScale = new Vector3(0.5f,0.5f,0.5f);
}

Related

How can i solve this error in Unity Curl error 3: url malformed

I'm trying to get the url from the php page where am I going wrong? Error is: Curl error 3: malformed
my php file output : https://akdenizsergi.com/yetki/uploads/test3.jpg
my php code:
<?php
echo "test3.jpg"
?>
my gettext code(C#):
IEnumerator GetText()
{
UnityWebRequest www = UnityWebRequest.Get("http://localhost/yetki/eserlistesi2.php");
yield return www.SendWebRequest();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
// Show results as text
eserurl = www.downloadHandler.text;
}
}
my get texture code:
IEnumerator GetTexture()
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture(eserurl);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log("hata" + www.error);
}
else
{
myTexture = ((DownloadHandlerTexture)www.downloadHandler).texture;
GetComponent<Renderer>().material = myMat;
// texture ı material e atıyor
myMat.mainTexture = myTexture;
// görsel ölçüsünü ekrana yazdırıyor
print("Size is " + myTexture.width + " by " + myTexture.height);
// plane ölçüsünü görselin ölçüsüne göre ayarlıyor
myPlane.transform.localScale += new Vector3(myTexture.width, 0, myTexture.height);
}
}

Any permanent solution this error "Download over http ,please consider updating to https" in Unity?

Trying to upload two different files into backend server.One is .json file and other is .worldmap file.When I upload I get this error in the debug "You are using download over http. Currently Unity adds NSAllowsArbitraryLoads to Info.plist to simplify transition, but it will be removed soon. Please consider updating to https.
Generic/unknown HTTP error"
I have noticed that sometimes this error shows up and sometimes not.From this Link solution the solution is to add UnityWebRequest.I have used that but still it continues to show up.Anything to do with my code ,webaddress or too many http calls from my code?
public void UploadMaps()
{
StartCoroutine(UploadFileData());
StartCoroutine(UploadWorldMap());
}
IEnumerator UploadFileData()
{
string mapnamedl = "pathtest";
Debug.Log("Mapname local = " + mapnamedl);
string locapath ="file://" +Application.persistentDataPath + "/" + mapnamedl + ".json";
Debug.Log("local path = " + locapath);
WWW localFile = new WWW(locapath);
yield return localFile;
if(localFile.error==null)
{
Debug.Log("Local file found successfully");
}
else
{
Debug.Log("Open file error: " + localFile.error);
yield break; // stop the coroutine here
}
Debug.Log("Form bytes = " + BitConverter.ToString(localFile.bytes));
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("Jsondata",localFile.bytes));
UnityWebRequest www = UnityWebRequest.Post("http://testsite.com/cab/test/save.php",formData);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string JSONDATAstring = www.downloadHandler.text;
Debug.Log("Json String is = " + JSONDATAstring);
JSONNode JNode = SimpleJSON.JSON.Parse(JSONDATAstring);
string login = (JNode["upload"][0]["success"]).ToString();
Debug.Log("login is = " + login);
if (login == "1")
{
Debug.Log("Form upload complete!");
}
else if (login == "0")
{
Debug.Log("Failed ");
}
}
}
IEnumerator UploadWorldMap()
// IEnumerator UploadFileData(string mapnamedl)
{
string mapnamedl = "pathtest";
Debug.Log("Mapname local = " + mapnamedl);
string locapath = "file://" + Application.persistentDataPath + "/" + mapnamedl + ".worldmap";
Debug.Log("local path = " + locapath);
WWW localFile = new WWW(locapath);
yield return localFile;
if (localFile.error == null)
{
Debug.Log("Local file found successfully");
}
else
{
Debug.Log("Open file error: " + localFile.error);
yield break; // stop the coroutine here
}
Debug.Log("Form bytes = " + BitConverter.ToString(localFile.bytes));
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("Jsondata", localFile.bytes));
UnityWebRequest www = UnityWebRequest.Post("http://testsite.com/cab/test/save.php", formData);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string JSONDATAstring = www.downloadHandler.text;
Debug.Log("Worldmap String is = " + JSONDATAstring);
JSONNode JNode = SimpleJSON.JSON.Parse(JSONDATAstring);
string login = (JNode["upload"][0]["success"]).ToString();
Debug.Log("Worldmap login is = " + login);
if (login == "1")
{
Debug.Log("Form upload complete!");
}
else if (login == "0")
{
Debug.Log("Failed ");
}
}
}
You're using the HTTP protocol (the http:// at the beginning of your URL). Apple enforces all kinds of random policies, one of which is that you must communicate over HTTPS, the secure version of HTTP. Try changing your URLs to https. If the server you're connecting to supports them, great. Otherwise, you'll need to make the server https-friendly by getting an HTTPS certificate and installing it on your server (if it's yours; otherwise, you're out of luck).

ASP.net Web API authorization denied with same credentials on Android in Unity3d [duplicate]

The Code below is used to get Temperature Value from Thingworx server that is hosted in one of our own systems. This works perfectly well in unity. But not in andoird, once apk is generated, it won't fetch any data from the server and there will be connection established. But, it just wont fetch the data and put that into the text mesh.
I'm using unity 5.4.1 32bit . Check in both Android - 5.0.2 and 6.
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using System.Text.RegularExpressions;
using System;
using UnityEngine.UI;
public class GETTempValue : MonoBehaviour {
public GameObject TempText;
static string TempValue;
void Start()
{
StartCoroutine(GetText());
}
IEnumerator GetText()
{
Debug.Log("Inside Coroutine");
while (true)
{
yield return new WaitForSeconds(5f);
string url = "http://Administrator:ZZh7y6dn#*IP Address*:8080/Thingworx/Things/SimulationData/Properties/OvenTemperature/";
Debug.Log("Before UnityWebRequest");
UnityWebRequest www = UnityWebRequest.Get (url);
yield return www.Send();
Debug.Log("After UnityWebRequest");
if (www.isError) {
Debug.Log ("Error while Receiving: "+www.error);
} else {
Debug.Log("Success. Received: "+www.downloadHandler.text);
string result = www.downloadHandler.text;
Char delimiter = '>';
String[] substrings = result.Split(delimiter);
foreach (var substring in substrings)
{
if (substring.Contains ("</TD"))
{
String[] Substrings1 = substring.Split ('<');
Debug.Log (Substrings1[0].ToString()+"Temp Value");
TempValue = Substrings1 [0].ToString ();
TempText.GetComponent<TextMesh> ().text = TempValue+"'C";
}
}
}
}
}
}
this is the android manifest permission
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Embedding username and password(http://username:password#example.com) in a url is no longer supported in some Applications and OS for security reasons.That's because this is not the standard way to perform HTTP Authentication. It very likely that Unity or Android did not implement this on the their side.
I tested this on the built-in Android Browser with http://Administrator:ZZh7y6dn#*IP Address*:8080/Thingworx/Things/SimulationData/Properties/OvenTemperature/ and it failed to function. So, I guess this problem is from Android.
I tested again without username and password http://*IP Address**:8080/Thingworx/Things/SimulationData/Properties/OvenTemperature/ then the login window appeared. When I entered the username and password, it worked.
You can still use UnityWebRequest to solve this problem by providing the AUTHORIZATION header to the UnityWebRequest with the SetRequestHeader function. This will only work if the authorization type is Basic instead of Digest. In your case, it is HTTP Basic.
For general solution:
string authenticate(string username, string password)
{
string auth = username + ":" + password;
auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
auth = "Basic " + auth;
return auth;
}
IEnumerator makeRequest()
{
string authorization = authenticate("YourUserName", "YourPassWord");
string url = "yourUrlWithoutUsernameAndPassword";
UnityWebRequest www = UnityWebRequest.Get(url);
www.SetRequestHeader("AUTHORIZATION", authorization);
yield return www.Send();
.......
}
For solution in your question:
public GameObject TempText;
static string TempValue;
void Start()
{
StartCoroutine(GetText());
}
string authenticate(string username, string password)
{
string auth = username + ":" + password;
auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
auth = "Basic " + auth;
return auth;
}
IEnumerator GetText()
{
WaitForSeconds waitTime = new WaitForSeconds(2f); //Do the memory allocation once
string authorization = authenticate("Administrator", "ZZh7y6dn");
while (true)
{
yield return waitTime;
string url = "http://*IP Address*:8080/Thingworx/Things/SimulationData/Properties/OvenTemperature/";
UnityWebRequest www = UnityWebRequest.Get(url);
www.SetRequestHeader("AUTHORIZATION", authorization);
yield return www.Send();
if (www.isError)
{
Debug.Log("Error while Receiving: " + www.error);
}
else
{
string result = www.downloadHandler.text;
Char delimiter = '>';
String[] substrings = result.Split(delimiter);
foreach (var substring in substrings)
{
if (substring.Contains("</TD"))
{
String[] Substrings1 = substring.Split('<');
Debug.Log(Substrings1[0].ToString() + "Temp Value");
TempValue = Substrings1[0].ToString();
TempText.GetComponent<TextMesh>().text = TempValue + "'C";
}
}
}
}
}

Receive image from web server C# Unity

I have had web server that stores the images. In Unity, I can receive one and create gameobject to change it's material. However, I want to receive max no. four images. After 1 mins, I want to receive max no. four images again. Besides, if there is two images in server, I just want to create two new gameobject and change them material. If there is three, just create three. How can I do that, Any one can help me? Here is my code in Unity:
void Start () {
StartCoroutine (LoadImage ());
}
IEnumerator LoadImage(){
filename = "image" + k.ToString () + ".png";
url = "https://wwwfoodparadisehk.000webhostapp.com/" + filename;
WWW www = new WWW (url);
yield return www;
if (www.error != null) {
Debug.Log (www.error);
} else {
Debug.Log (k);
path = "Assets/MyMaterial" + k.ToString () + ".mat";
k = k + 1;
material = new Material (Shader.Find ("Sprites/Default"));
AssetDatabase.CreateAsset (material, path);
Debug.Log (AssetDatabase.GetAssetPath (material));
material.mainTexture = www.texture;
GameObject newPaperInstance = Instantiate (newpaper) as GameObject;
newPaperInstance.transform.Find ("Plane001").gameObject.GetComponent<Renderer> ().material = material;
}
}
I'd first ask my server for a list of the items I can get. For this, you can simply make a text file or make your own PHP file to create a list that you separate by a character like the pipe (|):
MyMaterial1|MyMaterial2|MyMaterial3
Then you can ask the file from your server the same way you'd get the images and create a string[] array object from the result. You can use Split('|') in order to create this array from your result string.
When you're done, you can foreach over the items within the array.
IEnumerator LoadImages()
{
string filename = "imagelist.txt";
string url = "https://wwwfoodparadisehk.000webhostapp.com/" + filename;
WWW www = new WWW (url);
yield return www;
if (www.error != null)
{
Debug.Log (www.error);
}
else
{
string[] images = www.text.Split ('|');
foreach (var image in images)
{
LoadImage (image);
}
}
}
Last but not least, you'll have to create a second function that loads the texture from the string you supply:
IEnumerator LoadImage(string image)
{
string url = "https://wwwfoodparadisehk.000webhostapp.com/" + image;
WWW www = new WWW (url);
yield return www;
if (www.error != null)
{
Debug.Log (www.error);
}
else
{
// turn your image into a texture with www.texture and apply it to your objects.
}

Saving an Image to Photos Folder In hololens App

I'm attempting to capture a photo inside my hololens app. It seems to be working but saving the image to an obscure place that I cant access or view. I want to save it to my pictures library Described here I think. Or where should i save the image so I can see it in my photos on the hololens.
filePath = C:/Data/Users/JanikJoe/AppData/Local/Packages/HoloToolkit-Unity_pzq3xp76mxafg/LocalState\CapturedImage10.02831_n.jpg
filePath2 = C:/Data/Users/DefaultAccount/AppData/Local/DevelopmentFiles/HoloToolkit-UnityVS.Debug_x86.janik/Data\CapturedImage10.02831_n.jpg
using UnityEngine;
using UnityEngine.VR.WSA.WebCam;
using System.Linq;
public class PhotoCaptureFVTC : MonoBehaviour {
UnityEngine.VR.WSA.WebCam.PhotoCapture photoCaptureObject = null;
// Use this for initialization
void Start()
{
Debug.Log("snap pic taken");
PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
}
public void OnPhotoCaptureCreated(PhotoCapture captureObject)
{
photoCaptureObject = captureObject;
//Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
Resolution cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
CameraParameters c = new CameraParameters();
c.hologramOpacity = 0.0f;
c.cameraResolutionWidth = cameraResolution.width;
c.cameraResolutionHeight = cameraResolution.height;
c.pixelFormat = CapturePixelFormat.BGRA32;
captureObject.StartPhotoModeAsync(c, false, OnPhotoModeStarted);
}
void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
photoCaptureObject.Dispose();
photoCaptureObject = null;
}
private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
string filename = string.Format(#"CapturedImage{0}_n.jpg", Time.time);
string filePath = System.IO.Path.Combine(Application.persistentDataPath, filename);
string filePath2 = System.IO.Path.Combine(Application.dataPath, filename);
photoCaptureObject.TakePhotoAsync(filePath, PhotoCaptureFileOutputFormat.JPG, OnCapturedPhotoToDisk);
Debug.LogError("Saved That Image Somewhere" +"FileName: ="+ filename + " FilePath: = " + filePath + " FilePath2: = " + filePath2);
}
else
{
Debug.LogError("Unable to start photo mode!");
}
}
void OnCapturedPhotoToDisk(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
Debug.Log("Saved Photo to disk!");
photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode);
}
else
{
Debug.Log("Failed to save Photo to disk");
}
}
}
It seems to be that it is not possible to save directly in the camera roll folder and there is no picture library on the HoloLens.
There is the same question here: https://forums.hololens.com/discussion/1458/capturing-photo-in-unity-and-saving-to-disk
I tried the workaround and it works fine. Just move the saved image to the camera roll folder.
#if !UNITY_EDITOR && UNITY_WINRT_10_0
var cameraRollFolder = Windows.Storage.KnownFolders.CameraRoll.Path;
File.Move(_filePath, Path.Combine(cameraRollFolder, _filename));
#endif

Categories

Resources