WP8.1发送Post或Get请求顺带文件上传

    partial class Http
    {
        private CancellationTokenSource cts = new CancellationTokenSource();
        private HttpClient httpClient = new HttpClient();

        public Windows.Foundation.AsyncOperationWithProgressCompletedHandler<HttpResponseMessage, HttpProgress> CompletedHandler{ set; get; }
        public Windows.Foundation.AsyncOperationProgressHandler<HttpResponseMessage, HttpProgress> ProgressHandler { set; get; }

        /// <summary>
        /// 发送Get请求,需要在发送之前设置CompletedHandler,在CompletedHandler中取得返回的内容
        /// </summary>
        /// <param name="url">
        /// http://www.baidu.com
        /// </param>
        /// <return>
        /// void
        /// </return>
        public void Get(string url)
        {
            Uri uri = new Uri(url);
            var response = httpClient.GetAsync(uri);
            response.Completed = CompletedHandler;
            response.Progress = ProgressHandler;
        }

        /// <summary>
        /// 同上,发送Post请求 别忘了了设置CompletedHandler和ProgressHandler  不用的话就不用设置了
        /// </summary>
        /// <param name="url">
        /// http://www.baidu.com
        /// </param>
        /// <param name="postData">
        /// new List<KeyValuePair<string, string>>() {
        ///     new KeyValuePair<string,string>("username","username"),
        ///     new KeyValuePair<string,string>("password","password")
        /// }
        /// 服务器端接受$_POST['username'],$_POST['password']
        /// </param>
        /// <return>
        /// void
        /// </return>
        public void Post(string url,List<KeyValuePair<string,string>> postData)
        {
            Uri uri = new Uri(url);
            var response = httpClient.PostAsync(uri, new HttpFormUrlEncodedContent(postData));
            response.Completed = CompletedHandler;
            response.Progress = ProgressHandler;
        }

        /// <summary>
        /// 同上,发送post的请求,带文件的,别忘了了设置CompletedHandler和ProgressHandler  不用的话就不用设置了
        /// </summary>
        /// <param name="url">
        /// http://www.baidu.com
        /// </param>
        /// <param name="postData">
        /// new List<KeyValuePair<string,string>>(){
        ///     new KeyValuePair<string,string>("username","username"),
        ///     new KeyValuePair<string,string>("password","password")
        /// }
        /// 服务器端接受$_POST['username'] $_POST['password']
        /// </param>
        /// <param name="file">
        /// new List<KeyValuePair<string,StorageFile>>(){
        ///     new KeyValuePair<string,StorageFile>("file1",file1),
        ///     new KeyValuePair<string,StorageFile>("file2",file2),
        /// }
        /// 服务器端接受$_FILES['file1']  $_FILES['file2']
        /// </param>
        public void Post(string url,List<KeyValuePair<string,string>> keyValuePair,List<KeyValuePair<string,StorageFile>> files)
        {
            var postData = new HttpMultipartFormDataContent();
            foreach( var item in keyValuePair)
            {
                postData.Add(new HttpStringContent(item.Value), item.Key);
            }
            foreach( var item in files)
            {
                var fileTask = item.Value.OpenReadAsync().AsTask(cts.Token);
                var fileStream = new HttpStreamContent(fileTask.Result);
                postData.Add(fileStream, item.Key, item.Value.Name);
            }
            var response = httpClient.PostAsync(new Uri(url),postData);
            response.Completed = CompletedHandler;
            response.Progress = ProgressHandler;
        }

        /// <summary>
        /// 直接发送get请求,返回请求字符串
        /// </summary>
        /// <param name="url">
        /// http://www.baidu.com
        /// </param>
        /// <returns>
        /// string 请求的结果字符串
        /// </returns>
        public string GetTask(string url)
        {
            var response = httpClient.GetAsync(new Uri(url)).AsTask(cts.Token);
            var str = response.Result.Content.ReadAsStringAsync().AsTask(cts.Token);
            return str.Result;
        }

        /// <summary>
        /// 直接post直接返回响应字符串
        /// </summary>
        /// <param name="url">
        /// http://www.baidu.com
        /// </param>
        /// <param name="postData">
        /// new List<KeyValuePair<string, string>>() {
        ///     new KeyValuePair<string,string>("username","username"),
        ///     new KeyValuePair<string,string>("password","password")
        /// }
        /// 服务器端接受$_POST['username'],$_POST['password']
        /// </param>
        /// <returns></returns>
        public string PostTask(string url,List<KeyValuePair<string,string>> keyValuePair)
        {
            var postData = new HttpFormUrlEncodedContent(keyValuePair);
            var response = httpClient.PostAsync(new Uri(url), postData).AsTask(cts.Token);
            var str = response.Result.Content.ReadAsStringAsync().AsTask(cts.Token);
            return str.Result;
        }

        async public Task<string> GetAwait(string url)
        {
            var response = await httpClient.GetAsync(new Uri(url));
            var responseTask = await response.Content.ReadAsStringAsync();
            return responseTask;
        }

        public void Dispose()
        {
            httpClient.Dispose();
            httpClient = null;
            cts.Dispose();
            cts = null;
        }
    }


文件上传发现在服务器端无法接受到文件的mimetype,这点要注意

顺便提一下PHP获得文件的mimetype的方法,要准确的获得可能需要安装fileinfo扩展,否则只能根据后缀了

        /**
	 * 获得文件的MimeType
	 * @param string $file 文件路径
	 * @param int $options 返回的mime类型 可选 FILEINFO_MIME_TYPE || FILEINFO_MIME
	 * @param string $magicFile 魔法文件,设置为NULL 使用php内置的magicFile
	 * @return unknown|string|NULL
	 */
	public static function getMimeType($file,$options = FILEINFO_MIME_TYPE,$magicFile=NULL)
	{
		$result = finfo_file(finfo_open($options, $magicFile), $file);
		return $result?$result:self::getMimeTypeByExtension($file);
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值