C#笔记: 使用system.net.http与后台数据进行交互

(转载请注明来源:cnblogs coder-fang)

1。获取文件方式:

var param = new Dictionary<string, string> {

                 {"id", appmodel.imageid.ToString()},
                 {"isdownload","1"}
                 
             };

            try
            {
                HttpContent httpContent = new FormUrlEncodedContent(param);                
                HttpClient client = new HttpClient();
                httpContent.Headers.Add("token", getSysinfo().token);

                HttpResponseMessage response = client.PostAsync(DiagUrl + "/service/getfile", httpContent).Result;

                String statusCode = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    
                    byte[] result = response.Content.ReadAsByteArrayAsync().Result;
                    if(result==null || result.Length <=0)
                    {
                        errcall("没有此文件");
                        return;                    
                    }
                    String path=ConfigService.ReportDir;
                    if(!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    path+=appmodel.name+"_"+appmodel.modality+".pdf";
                    
                    Stream outStream = System.IO.File.Create(path);

                    outStream.Write(result, 0, result.Length);
                    outStream.Flush();
                    outStream.Close();
                    success("已保存:\r\n"+path);
                }
                else
                {
                    errcall("获取失败:" + response.StatusCode);
                }
            }
            catch (Exception e)
            {

                errcall("访问服务失败: " + e.Message + "\r\n" );
            }
View Code

2。发送普通参数并处理json返回:

public void AddIDCard(int id,String idcard, Action<Object> success, Action<object> errcall)
        {
            var param = new Dictionary<string, string> {

                 {"id", id.ToString()},
                 {"cardid",idcard}
                 
             };

            try
            {
                HttpContent httpContent = new FormUrlEncodedContent(param);
                httpContent.Headers.Add("token", getSysinfo().token);
                HttpClient client = new HttpClient();

                HttpResponseMessage response = client.PostAsync(DiagUrl + "/service/setcard", httpContent).Result;

                String statusCode = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    string result = response.Content.ReadAsStringAsync().Result;
                    success(JsonConvert.DeserializeObject(result));
                }
                else
                {
                    errcall("设置信息失败:" + response.StatusCode);
                }
            }
            catch (Exception e)
            {

                errcall("访问服务失败: " + e.Message + "\r\n" );
            }
        }
View Code

3。使用普通url方式发送信息:

public void SendUpload(Dictionary<string, string> data, Action<Object> success, Action<object> errcall)
        {           
            try
            {
               
                String urlString = "";
                foreach (var key in data.Keys)
                {
                    urlString += string.Format("{0}={1}&", key, HttpUtility.UrlEncode(data[key]));
                }
                

                HttpContent httpContent = new StringContent(urlString.Substring(0, urlString.Length - 1), Encoding.UTF8);
                httpContent.Headers.Remove("Content-Type");//必须
                httpContent.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//1.根据需求设置            

                HttpClient client = new HttpClient();
                HttpResponseMessage response = client.PostAsync(UploadUrl, httpContent).Result;
                
                String statusCode = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    string result = response.Content.ReadAsStringAsync().Result;
                    success(JsonConvert.DeserializeObject(result));
                }
                else
                {
                    errcall("发送信息失败" );
                }
            }
            catch (Exception e)
            {

                errcall("访问服务失败: " + e.Message + "\r\n" );
            }

        }
View Code

4。发送格式化模型json数据:

public void SaveTempDetail(TempDetailModel detail,Action<Object> success, Action<object> errcall)
        {
            string body = JsonConvert.SerializeObject(detail);
            try
            {
                HttpContent httpContent = new StringContent(body);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                httpContent.Headers.Add("Type", "exe");
                httpContent.Headers.Add("username", getSysinfo().account);
                httpContent.Headers.Add("token", getSysinfo().token);
                HttpClient client = new HttpClient();


                HttpResponseMessage response = client.PostAsync(URL + "template/saveTepdetails", httpContent).Result;

                String statusCode = response.StatusCode.ToString();
                if (response.IsSuccessStatusCode)
                {
                    string result = response.Content.ReadAsStringAsync().Result;
                    success(JsonConvert.DeserializeObject(result));
                }
                else
                {
                    errcall("修改模板信息失败:" + response.StatusCode);
                }

            }
            catch (Exception e)
            {
                errcall("访问服务失败: " + e.Message + "\r\n" );
            }
        }
View Code

 

posted @ 2019-07-23 08:37  Coder_fang  阅读(1907)  评论(0编辑  收藏  举报