MultipartBody.Builder PrepareRequest(IDictionary <string, string> parameters = null, string boundary = null)
        {
            MultipartBody.Builder requestBodyBuilder = null;

            if (string.IsNullOrEmpty(boundary))
            {
                requestBodyBuilder = new MultipartBody.Builder().SetType(MultipartBody.Form);
            }
            else
            {
                requestBodyBuilder = new MultipartBody.Builder(boundary).SetType(MultipartBody.Form);
            }

            if (parameters != null)
            {
                foreach (string key in parameters.Keys)
                {
                    if (parameters[key] != null)
                    {
                        requestBodyBuilder.AddFormDataPart(key, parameters[key]);
                    }
                }
            }
            return(requestBodyBuilder);
        }
        FileUploadResponse MakeRequest(string url, string tag, MultipartBody.Builder requestBodyBuilder, IDictionary <string, string> headers = null)
        {
            //RequestBody requestBody = requestBodyBuilder.Build();
            CountingRequestBody requestBody = new CountingRequestBody(requestBodyBuilder.Build(), tag, this);
            var requestBuilder = new Request.Builder();

            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    if (!string.IsNullOrEmpty(headers[key]))
                    {
                        requestBuilder = requestBuilder.AddHeader(key, headers[key]);
                    }
                }
            }

            Request request = requestBuilder
                              .Url(url)
                              .Post(requestBody)
                              .Build();

            var builder = new OkHttpClient.Builder();

            builder.ConnectTimeout(ConnectUploadTimeout, UploadTimeoutUnit);
            builder.ReadTimeout(SocketUploadTimeout, UploadTimeoutUnit);

            var client = builder.Build();

            Response response       = client.NewCall(request).Execute();
            var      responseString = response.Body().String();
            var      code           = response.Code();

            IDictionary <string, string> responseHeaders = new Dictionary <string, string>();
            var rHeaders = response.Headers();

            if (rHeaders != null)
            {
                var names = rHeaders.Names();
                foreach (string name in names)
                {
                    if (!string.IsNullOrEmpty(rHeaders.Get(name)))
                    {
                        responseHeaders.Add(name, rHeaders.Get(name));
                    }
                }
            }

            FileUploadResponse fileUploadResponse = new FileUploadResponse(responseString, code, tag, new ReadOnlyDictionary <string, string>(responseHeaders));


            if (response.IsSuccessful)
            {
                FileUploadCompleted(this, fileUploadResponse);
            }
            else
            {
                FileUploadError(this, fileUploadResponse);
            }

            return(fileUploadResponse);
        }
Exemple #3
0
        /// <summary>
        /// 执行上传
        /// </summary>
        /// <param name="p_uploadFiles">待上传文件</param>
        /// <param name="p_fixedvolume">要上传的固定卷名,null表示上传到普通卷</param>
        /// <param name="p_tokenSource">取消上传的令牌,不负责释放</param>
        /// <returns></returns>
        public static async Task <List <string> > Send(IList <FileData> p_uploadFiles, string p_fixedvolume, CancellationTokenSource p_tokenSource)
        {
            // 列表内容不可为null
            if (p_uploadFiles == null ||
                p_uploadFiles.Count == 0 ||
                p_uploadFiles.Contains(null))
            {
                return(null);
            }

            var bodyBuilder = new MultipartBody.Builder().SetType(MultipartBody.Form);

            if (!string.IsNullOrEmpty(p_fixedvolume))
            {
                // 固定上传路径放在最前
                bodyBuilder.AddFormDataPart("fixedvolume", p_fixedvolume);
            }

            foreach (var uf in p_uploadFiles)
            {
                Java.IO.File file = new Java.IO.File(uf.FilePath);
                RequestBody  rb   = RequestBody.Create(file, MediaType.Parse("application/octet-stream"));
                // 包一层实现进度
                ProgressRequestBody progress = new ProgressRequestBody(rb, ((IUploadUI)uf.UploadUI).UploadProgress);
                bodyBuilder.AddFormDataPart(uf.Desc, uf.FileName, progress);

                // 含缩略图
                if (!string.IsNullOrEmpty(uf.ThumbPath))
                {
                    var thumbFile = new Java.IO.File(uf.ThumbPath);
                    var thumb     = RequestBody.Create(thumbFile, MediaType.Parse("application/octet-stream"));
                    bodyBuilder.AddFormDataPart("thumbnail", "thumbnail.jpg", thumb);
                }
            }
            RequestBody body = bodyBuilder.Build();

            var request = new Request.Builder()
                          .Post(body)
                          .Url($"{Kit.Stub.ServerUrl.TrimEnd('/')}/fsm/.u");

            if (Kit.IsLogon)
            {
                request.Header("uid", Kit.UserID.ToString());
            }

            var call = _client.NewCall(request.Build());

            p_tokenSource.Token.Register(() => Task.Run(() => call.Cancel()));
            _tokenSource = p_tokenSource;

            Response resp;

            try
            {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
            }
            catch
            {
                return(null);
            }
            finally
            {
                _tokenSource = null;
            }

            var result = resp.Body().Bytes();

            if (result == null || result.Length == 0)
            {
                return(null);
            }
            return(ParseResult(result));
        }