Unity C#GraphQL发布请求正文身份验证

时间:2018-04-13 14:49:50

标签: c# unity3d graphql

我正在尝试连接我的开发人员在Unity中设置的GraphQL服务器。我找到了一些脚本来帮助这个过程,但是,我仍然无法连接因为我需要登录系统托管graphql才能从外部查询,我不能只使用端点网址。

我的开发人员告诉我对mysystem / login进行POST请求,并在请求正文中添加{email:string,password:string}。我尝试了一些不同的东西,没有任何工作。我必须使用电子邮件和密码登录mysystem / login,然后我将能够从下面的代码连接到mygraphql端点.--我假设这部分将转到我有// smt身份验证说明的地方。任何有关如何设置发布请求以及它应该在何处或如何工作的帮助都将非常感激。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using SimpleJSON;
using UnityEngine;
using UnityEngine.Networking;

namespace graphQLClient
{
public class GraphQuery : MonoBehaviour
{
    public static GraphQuery instance = null;
    [Tooltip("The url of the node endpoint of the graphQL server being queried")]
    public static string url;

    public delegate void QueryComplete();
    public static event QueryComplete onQueryComplete;

    public enum Status { Neutral, Loading, Complete, Error };

    public static Status queryStatus;
    public static string queryReturn;

    string authURL;
    public static string LoginToken;

    public class Query
    {
        public string query;
    }

    public void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(gameObject);

        StartCoroutine("PostLogin");
    }

    private void Start()
    {
        LoginToken = "";
    }

    public static Dictionary<string, string> variable = new Dictionary<string, string>();
    public static Dictionary<string, string[]> array = new Dictionary<string, string[]>();
    // Use this for initialization

    // SMT Authentication to ELP
    // SMT Needed for Authentication---  if (token != null) request.SetRequestHeader("Authorization", "Bearer " + token);
    //In the request body: {email: string, password: string}
    //You’ll either get a 401 with an empty response or 201 with {token: string, user: object}
    IEnumerator PostLogin()
    {
        Debug.Log("Logging in...");
        string authURL = "https://myapp.com/login";
        string loginBody = "{\"email\":\"myemail.com\",\"password\":\"mypassowrd\"}";

        var request = new UnityWebRequest(authURL, "POST");
        byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(loginBody);
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return request.SendWebRequest();

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log("Login error!");

            foreach (KeyValuePair<string, string> entry in request.GetResponseHeaders())
            {
                Debug.Log(entry.Value + "=" + entry.Key);
            }

            Debug.Log(request.error);
        }
        else
        {
            Debug.Log("Login complete!");
            //Debug.Log(request.downloadHandler.text);
            LoginToken = request.downloadHandler.text;
            Debug.Log(LoginToken);
        }
    }

    public static WWW POST(string details)
    {
        //var request = new UnityWebRequest(url, "POST");
        details = QuerySorter(details);
        Query query = new Query();
        string jsonData = "";
        WWWForm form = new WWWForm();
        query = new Query { query = details };
        jsonData = JsonUtility.ToJson(query);
        byte[] postData = Encoding.ASCII.GetBytes(jsonData);
        Dictionary<string, string> postHeader = form.headers;
        //postHeader["Authorization"] = "Bearer " + downloadHandler.Token;
        if (postHeader.ContainsKey("Content-Type"))

            //postHeader["Content-Type"] = "application/json";
            postHeader.Add("Authorization", "Bearer " + LoginToken);


        else
            //postHeader.Add("Content-Type", "application/json");
            postHeader.Add("Authorization", "Bearer " + LoginToken);


        WWW www = new WWW(url, postData, postHeader);
        instance.StartCoroutine(WaitForRequest(www));
        queryStatus = Status.Loading;
        return www;
    }

    static IEnumerator WaitForRequest(WWW data)
    {
        yield return data; // Wait until the download is done
        if (data.error != null)
        {
            Debug.Log("There was an error sending request: " + data.error);
            queryStatus = Status.Error;
        }
        else
        {
            queryReturn = data.text;
            queryStatus = Status.Complete;
        }
        onQueryComplete();
    }

    public static string QuerySorter(string query)
    {
        string finalString;
        string[] splitString;
        string[] separators = { "$", "^" };
        splitString = query.Split(separators, StringSplitOptions.RemoveEmptyEntries);
        finalString = splitString[0];
        for (int i = 1; i < splitString.Length; i++)
        {
            if (i % 2 == 0)
            {
                finalString += splitString[i];
            }
            else
            {
                if (!splitString[i].Contains("[]"))
                {
                    finalString += variable[splitString[i]];
                }
                else
                {
                    finalString += ArraySorter(splitString[i]);
                }
            }
        }
        return finalString;
    }

    public static string ArraySorter(string theArray)
    {
        string[] anArray;
        string solution;
        anArray = array[theArray];
        solution = "[";
        foreach (string a in anArray)
        {

        }
        for (int i = 0; i < anArray.Length; i++)
        {
            solution += anArray[i].Trim(new Char[] { '"' });
            if (i < anArray.Length - 1)
                solution += ",";
        }
        solution += "]";
        Debug.Log("This is solution " + solution);
        return solution;
    }

}
}

0 个答案:

没有答案