【问题标题】:How to update user picture using PUT method in Unity3D如何在 Unity3D 中使用 PUT 方法更新用户图片
【发布时间】:2019-02-04 18:19:03
【问题描述】:

我是 Unity3D 的初学者;我必须开发一个移动应用程序,并且我需要管理用户个人资料数据;我必须使用 REST 服务与服务器通信这些数据。 当我从我的应用程序发送 Json(例如姓名、电子邮件、电话号码等)时,一切正常,但我无法更新个人资料图片。

我需要的是: 内容类型 = 多部分/表单数据 key="profile_picture", value=file_to_upload(不是路径)

我在 Unity 中阅读了很多关于网络的信息,并尝试了 UnityWebRequest、List、WWWform 的不同组合,但对于这种 PUT 服务似乎没有任何效果。

UnityWebRequest www = new UnityWebRequest(URL + user.email, "PUT");
    www.SetRequestHeader("Content-Type", "multipart/form-data");
    www.SetRequestHeader("AUTHORIZATION", authorization);
    //i think here i'm missing the correct way to set up the content

我可以正确模拟来自 Postman 的更新,所以这不是服务器的问题;我很确定问题是我无法在应用程序内转换此逻辑。

从 Postman 上传正常工作(1)

从 Postman 上传正常工作(2)

我们将不胜感激任何类型的帮助和代码建议。 谢谢

【问题讨论】:

标签: c# rest unity3d client-server


【解决方案1】:

使用Put,您通常只发送文件数据而没有表单。

您可以使用UnityWebRequest.Post添加多部分表单

IEnumerator Upload() 
{
    List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
    formData.Add(new MultipartFormFileSection("profile_picture", byte[], "example.png", "image/png"));

    UnityWebRequest www = UnityWebRequest.Post(url, formData);

    // change the method name
    www.method = "PUT"; 

    yield return www.SendWebRequest();

    if(www.error) 
    {
        Debug.Log(www.error);
    }
    else 
    {
        Debug.Log("Form upload complete!");
    }
}

使用MultipartFormFileSection


或者您也可以使用WWWForm

IEnumerator Upload()
{
    WWWForm form = new WWWForm();
    form.AddBinaryData("profile_picture", bytes, "filename.png", "image/png");

    // Upload via post request
    var www = UnityWebRequest.Post(screenShotURL, form);

    // change the method name
    www.method = "PUT";        

    yield return www.SendWebRequest();

    if (www.error) 
    {
        Debug.Log(www.error);
    }
    else 
    {
        Debug.Log("Finished Uploading Screenshot");
    }
}

使用WWWForm.AddBinaryData


请注意,对于用户身份验证,您必须正确编码您的凭据:

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;
}

www.SetRequestHeader("AUTHORIZATION", authenticate("user", "password"));

(Source)

【讨论】:

  • 这比我尝试的要好,但它给我带来了同样的错误:如果我使用 POST 请求,我有错误 405,因为 POST 请求没有在服务器上实现。另一方面,如果我尝试仅上传文件,则会出现错误 500。使用邮递员,我可以正确使用 PUT 服务
  • Afaik 没有使用 PUT 发送多格式数据的标准方法。但是,您可能会尝试使用 www.method = "PUT"; 之类的东西来简单地更改方法
  • 我只包含了用户身份验证,我只是在这种情况下有问题
  • 这是一个很好的解决方法。请记住,MultipartFormFileSection 可能需要 derHugo 指定的所有“四个参数”
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多