HttpWebRequest发布用于AWS文件上传请求的参数,导致400错误 [英] HttpWebRequest post paramaters for AWS file upload request, leading to 400 error

查看:110
本文介绍了HttpWebRequest发布用于AWS文件上传请求的参数,导致400错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件从Unity游戏上传到我的AWS账户.可以在此处找到执行此操作的表格.早些时候,我使用FILEUPLOAD_BASE_URL作为" https://file.ac/xySSFOicMMk/"不需要密钥即可上传文件(链接此处).但是,AWS文件上传需要格式为"/$ {filename}"的键参数.我将值指定为sb.Append("key: AffectivaLogs/${filename}");,如下所示,但是请求抛出400错误.这是将密钥指定为发布请求参数的正确方法吗?

I am trying to upload files from my Unity game to my AWS account. The form for doing this can be found here. Earlier I was using FILEUPLOAD_BASE_URL to be "https://file.ac/xySSFOicMMk/" which doesn't require a key to upload the file (link here). However, the AWS file upload require a key param in the form whose value can be "/${filename}". I specified the value as sb.Append("key: AffectivaLogs/${filename}"); as shows below, but the request is throwing a 400 error. Is this the correct way to specify the key as a post request parameter?

private string FILEUPLOAD_BASE_URL = "http://gameexperiencesurvey.s3.amazonaws.com/";
public void uploadToDrive()
{    
    string[] files = Directory.GetFiles(".", "*.txt");
    for (int i = 0; i < files.Length; i++)
    {
        string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
        ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(FILEUPLOAD_BASE_URL);
        webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
        webrequest.Method = "POST";
        // Build up the post message header  
        StringBuilder sb = new StringBuilder();
        sb.Append("--");
        sb.Append(boundary);
        sb.Append("\r\n");
        sb.Append("key: AffectivaLogs/${filename}"); // is this how it should be?
        sb.Append("\r\n");
        sb.Append("Content-Disposition: form-data; name=\"");
        sb.Append("file"); // file form name
        sb.Append("\"; filename=\"");
        sb.Append(Path.GetFileName(files[i]));
        sb.Append("\"");
        sb.Append("\r\n");
        sb.Append("Content-Type: ");
        sb.Append("text/plain");
        sb.Append("\r\n");
        sb.Append("\r\n");

        string postHeader = sb.ToString();
        byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

        // Build the trailing boundary string as a byte array  
        // ensuring the boundary appears on a line by itself  
        byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read);
        long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
        webrequest.ContentLength = length;

        Stream requestStream = webrequest.GetRequestStream();

        // Write out our post header  
        requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

        // Write out the file contents  
        byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            requestStream.Write(buffer, 0, bytesRead);

        // Write out the trailing boundary  
        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        try
        {
            WebResponse response = webrequest.GetResponse();
            Stream s = response.GetResponseStream();
            StreamReader sr = new StreamReader(s);
        }
        catch (Exception e)
        {
            Debug.Log("Error occured .... " + e.Message);
        }        
    }
}

public bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    bool isOk = true;
    // If there are errors in the certificate chain, look at each error to determine the cause.
    if (sslPolicyErrors != SslPolicyErrors.None)
    {
        for (int i = 0; i < chain.ChainStatus.Length; i++)
        {
            if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown)
            {
                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
                bool chainIsValid = chain.Build((X509Certificate2)certificate);
                if (!chainIsValid)
                {
                    isOk = false;
                }
            }
        }
    }
    return isOk;
}

错误如下:

推荐答案

昨天我试图使用WWWForm和WWW上载文件,但我遇到了

Yesterday I was trying to use WWWForm and WWW to upload file and I had a problem where adding the binary data to WWWform was not working. Seems like in order for WWWForm to work, you need to have both the binary and non-binary data in your form. Thus, the following solution worked.

public void uploadToAWS()
{
    fileNameList = "";
    string[] files = Directory.GetFiles(".", "*.txt");
    for (int i = 0; i < files.Length; i++)
    {
        WWWForm AWSform = new WWWForm();
        AWSform.AddField("key", "AffectivaLogs/${filename}");
        AWSform.AddBinaryData("file", File.ReadAllBytes(files[i]), files[i], "text/plain");
        StartCoroutine(Post(FILEUPLOAD_BASE_URL, AWSform));
        fileNameList += files[i].Replace(@".\", "") + "  ||  ";
    }
} 
IEnumerator Post(string url, WWWForm form)
{               
    WWW www = new WWW(url, form);
    float elapsedTime = 0.0f;
    while (!www.isDone)
    {
        elapsedTime += Time.deltaTime;
        //Matrix4x4 wait time is 20s
        if (elapsedTime >= 20f)
        {
            break;
        }
        yield return null;
    }
    if (!www.isDone || !string.IsNullOrEmpty(www.error))
    {
        Debug.LogError("Connection error while sending analytics... Error:" + www.error);
        // Error handling here.
        yield break;
    }

    if (www.isDone)
    {            
        Debug.Log("Data Sent successfully.");
        yield break;
    }        
}

这篇关于HttpWebRequest发布用于AWS文件上传请求的参数,导致400错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆