◄ Unity 『功能总结』►——后台对接(登录//图片上传//图片加载)POST/GET混合使用

后台对接POST/GET混合使用

  • 1.账号登录
  • 2.加载图片
  • 3.上传图片

1.账号登录

接口形式 http://jia.111.com:222/333/login?username=123&password=123


GET形式


注意!我的后台端传送的都是以json数据传输


实例:
http://jia.111.com:222/333/login? username=123 & password=123
3个警示地方为
http://jia.111.com:222/333/login? 你的地址
username=123 & password=123 你的传参(等号前面是你后台给你参数接口,后面123则为你的传参)


如上, 下文的 (int)jd[“code”]/ 也是后台给你的返回参数

 IEnumerator Login() // GET
    {
        //服务器地址
        string url = "url";
        //get请求的接口
        string getInterface = "login?";
        //传给服务器的数据,?开头,每条数据以key=value的形式用&拼接起来
        string getParams = "username=" + InputField_Acc.text + "&password=" + InputField_Pass.text;
        UnityWebRequest _UnityWebRequest = UnityWebRequest.Get(url + getInterface + getParams);

        yield return _UnityWebRequest.SendWebRequest();

        if (_UnityWebRequest.isHttpError || _UnityWebRequest.isNetworkError)
        {
            Debug.Log(_UnityWebRequest.error);
        }
        else
        {
            Debug.Log(_UnityWebRequest.downloadHandler.text);

            //这里是解析,包括整形与字符串  
            JsonData jd = JsonMapper.ToObject(_UnityWebRequest.downloadHandler.text);

            yield return jd;

            if ((int)jd["code"] == 500)
            {
                printe("账号或密码错误");
            }
            else if ((int)jd["code"] == 200)
            {       
                printe("登录成功");
            }
        }
    }



2.加载图片

接口形式 http://jia.111.com:222/333/list?username=123


GET形式


注意!我的后台端传送的都是以json数据传输


实例:
http://jia.111.com:222/333/login? username=123
3个警示地方为
http://jia.111.com:222/333/login? 你的地址
username=123 你的传参(等号前面是你后台给你参数接口,后面123则为你的传参)

  IEnumerator DownLoadPic()
    {
        //服务器地址
        string url = "url1";
        //get请求的接口
        string getInterface = "list?";
        //传给服务器的数据,?开头,每条数据以key=value的形式用&拼接起来
        string getParams = "username=" + "waa";
        UnityWebRequest _UnityWebRequest = UnityWebRequest.Get(url + getInterface + getParams);

        yield return _UnityWebRequest.SendWebRequest();

        if (_UnityWebRequest.isHttpError || _UnityWebRequest.isNetworkError)
        {
            Debug.Log(_UnityWebRequest.error);
        }
        else
        {
            Debug.Log(_UnityWebRequest.downloadHandler.text);

            //这里是解析,包括整形与字符串  
            JsonData jd = JsonMapper.ToObject(_UnityWebRequest.downloadHandler.text);
            yield return jd;


            if ((int)jd["code"] == 500)
            {
                print("加载失败");
            }
            else if ((int)jd["code"] == 200)
            {
                //获取全部图片
                for (int i = 0; i < jd["result"].Count; i++)
                {
                	//直接使用Rawiamage  调用Texture2D直接赋图
                    RawImage newRaw = Instantiate(Item_ShowRaw, ShowRawConten);
                    WWW www = new WWW("url2" + (string)jd["result"][i]["url"]);
                    yield return www;
                    newRaw.texture = www.texture;
                    newRaw.SetNativeSize();

                    //图片大小 同一图片大小比例
                    RectTransform rectTransform = newRaw.GetComponentInChildren<RectTransform>();
                    float proportionX = 455 / rectTransform.sizeDelta.x;
                    float proportionY = 455 / rectTransform.sizeDelta.y;
                    float proportionEnd = 0;
                    if (proportionX > proportionY)
                        proportionEnd = proportionY;
                    else
                        proportionEnd = proportionX;

                    rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x * proportionEnd, rectTransform.sizeDelta.y * proportionEnd);

                    newRaw.name = (string)jd["result"][i]["imgName"];
                }

                print("加载成功");
            }
        }
      
    }



3.上传图片

接口形式 http://jia.111.com:222/333


POST形式 WWWForm表格发送


注意!我的后台端传送的都是以json数据传输


实例:

http://jia.111.com:222/333/
http://jia.111.com:222/333/ 你的地址
WWWForm 传参 跟后台沟通 需要发送什么数据。 我的是发送username文件就好了

    IEnumerator Upload(string uploadtextureURL, string texturename)
    {
        byte[] bytes = GetTexrture2DFromPath(uploadtextureURL);//获取图片数据
        yield return bytes;
        WWWForm form = new WWWForm();//创建提交数据表单
        form.AddField("username", ID);//用户名-文件名
        form.AddBinaryData("file", bytes, texturename);//字段名,文件数据,文件名
        WWW www = new WWW("http://jia.111.com:222/333/", form);
        yield return www;
        print(www.text);

        JsonData jd = JsonMapper.ToObject(www.text);

        if (www.error != null)
        {
            print(www.error);
        }
        if (www.isDone)
        {
            if ((int)jd["code"] == 200)
            {
                    print("上传成功");
            }
            else if ((int)jd["code"] == 500) 
            {
            	//这是返回参数检测时含有中文  需要跟后台沟通
                if ( (string)jd["message"] ==  "Failed to parse multipart servlet request; nested exception is java.lang.NoClassDefFoundError: javax/mail/internet/MimeUtility")
                {
                    print("检查图片是否含有中文或文件夹含有中文!");
                }
                else
                {
                    print("上传失败");
                }
            }
        }
    }

转换图片为bytes

  public static byte[] GetTexrture2DFromPath(string imgPath)
    {
        //读取文件
        FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
        int byteLength = (int)fs.Length;
        byte[] imgBytes = new byte[byteLength];
        fs.Read(imgBytes, 0, byteLength);
        fs.Close();
        fs.Dispose();
        return imgBytes;
    }

选取图片(外部选取调用FileDialog)

   void OpenFileDownLoadFunction()
    {
        OpenFileName ofn = new OpenFileName();

        ofn.structSize = Marshal.SizeOf(ofn);

        ofn.filter = "所有图片格式(.bmp;.jpeg;.jpg;.png;)\0*.bmp;*.jpeg;*.jpg;*.png;";

        ofn.file = new string(new char[256]);

        ofn.maxFile = ofn.file.Length;

        ofn.fileTitle = new string(new char[64]);

        ofn.maxFileTitle = ofn.fileTitle.Length;

        ofn.initialDir = UnityEngine.Application.dataPath;//默认路径

        ofn.title = "选择你的的图片:";
        
        //注意 一下项目不一定要全选 但是0x00000008项不要缺少
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR

        ofn.dlgOwner = LocalDialog.GetForegroundWindow(); //这一步将文件选择窗口置顶。

        if (LocalDialog.GetSaveFileName(ofn))
        {
            //上传
            StartCoroutine(Upload(ofn.file, ofn.fileTitle));
        }

    }

供应上面外部调取文件 => OpenFileDownLoadFunction

using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{
    #region Config Field
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
    #endregion


    #region Win32API WRAP
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    static extern bool GetOpenFileName([In, Out] LocalDialog dialog);  //这个方法名称必须为GetOpenFileName
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    static extern bool GetSaveFileName([In, Out] LocalDialog dialog);  //这个方法名称必须为GetSaveFileName
    #endregion
}

public class LocalDialog
{
    //链接指定系统函数       打开文件对话框
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
    public static bool GetOFN([In, Out] OpenFileName ofn)
    {
        return GetOpenFileName(ofn);
    }

    //链接指定系统函数        另存为对话框
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetSaveFileName([In, Out] OpenFileName ofn);
    public static bool GetSFN([In, Out] OpenFileName ofn)
    {
        return GetSaveFileName(ofn);
    }

    //窗口置顶
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

}

你可能感兴趣的:(◄,Unity,『功能总结』►,unity,服务器,游戏引擎)