- Home /
login to the server in unity c#
hi there,
i am trying to login to a server via unity c# script,
serverUrl "someapi" . which is of type "GET" on server.
if i open this links in any browser it gives a authentication popup, i put username and password and it's login and show the user details.
but when i try to do it via unity c# script, it gives me error code 401 >> unauthorised.
i have tried in different ways like >> www(); and unitywebrequest();
here is the code functions which i am using ;
public class UserClassForLogin { public string username = ""; public string password = "";
public string SetValuesForLogin() { UserClassForLogin temp = new UserClassForLogin();
temp.username = username1;
temp.password = username1;
string userJsonfile = JsonUtility.ToJson(temp);
return userJsonfile;
}
IEnumerator ServerRequestForLogin() {
// 1st try // not working error 401 >> unauthorised
var newUserJson = SetValuesForLogin();
string tempUrl =someapi;
tempUrl = tempUrl.Replace(" ", "%20");
UnityWebRequest request = UnityWebRequest.Put(tempUrl, newUserJson);
byte[] rawData = System.Text.Encoding.ASCII.GetBytes(newUserJson.ToCharArray());
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(rawData);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.Send();
var can = true;
while (can)
{
if (!request.isDone)
{
Debug.Log("downloading");
}
else if (request.isDone)
{
Debug.Log(request.responseCode);
Debug.Log("pre planed : " + Username + " " + Password);
can = false;
}
}
// 2st try // not working error 401 >> unauthorised
string tempUrl = someapi;
tempUrl = tempUrl.Replace(" ", "%20");
var form = new WWWForm();
form.AddField("Username", Username);
form.AddField("Password", Password);
var headers = form.headers;
var rawData = form.data;
var secretKey = Username + ":" + Password;
headers["Authorization"]="Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(secretKey));
var api = new WWW(tempUrl,rawData,headers);
}
and i have tried some more code and nothing works for me.
some thing i am doing wrong, i don't know what.