c#中使用httpclient进行两个网站的通信

关于在c#中使用httpclient的实例:

客户端代码:客户端部分我会传两个实体对象加一个图片流

  public  ActionResult HttpClientDoGet(int Id)
        {
            
            var myyonghu = EF.yonghu.Find(3);
            var mybook = EF.books.Find(Id);
            Image img = new Bitmap(Server.MapPath(mybook.picpath));   //图片转换为流
            MemoryStream stream = new MemoryStream();
            img.Save(stream, ImageFormat.Bmp);
            BinaryReader br = new BinaryReader(stream);
            byte[] bytes = stream.ToArray();
            stream.Close();
            var jsonSetting= new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore };//去除为空的对象属性
            var mybookoo = JsonConvert.SerializeObject(new {mybook, myyonghu,bytes },Formatting.Indented,jsonSetting);  //mybook,myyonghu,bytes必须与服务器端的名称相对应
            HttpContent httpContent = new StringContent(mybookoo);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");//定义http的头文件
            var httpClient = new HttpClient();

           //下面的try catch部分我只判断两种状态,链接的了的返回success,链接不了的返回链接失败
            try
            {
                var responseJson = httpClient.PostAsync("http://192.168.2.101:8888/api/Charging/GetAllChargingData/", httpContent)
              .Result.Content.ReadAsStringAsync().Result;

                return Content("success");
            }
            catch (Exception)
            {
                return Content("链接失败!");
            }
        }

    关于url错误或者服务器被关闭而无法发起请求,这一部分的内容我还不太了解,望有大神了解的不吝赐教!

//服务器端

  [HttpPost]
        public HttpResponseMessage GetAllChargingData(Allbook mybook1)
        {
           
            MemoryStream ms = new MemoryStream(mybook1.bytes);
            ms.Position = 0;
            string ImagePath = System.Web.Hosting.HostingEnvironment.MapPath( "/css/" + new FileUp().RndName() + ".jpg");//webapi中不能使用Server.Mappath
            Bitmap bmp = new Bitmap(ms);
            bmp.Save(ImagePath);
            ms.Close();
            books newbook = new books();
            newbook.unit3 = mybook1.mybook.unit3;

            yonghu  newyonghu=new yonghu();

           newyonghu.bookname = mybook1.myyonghu.surname;
            EF.books.Add(newbook);

           EF.yonghu.Add(newbook);
           EF.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.OK, "ok");       //当执行成功,statuscode是OK时,返回字符ok   
        }

实体扩展类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace xpt.Models
{
    public class Allbook
    {
        public books mybook { get; set; }//books类
        public yonghu myyonghu { get; set; }
        public byte[] bytes { get; set; }//用于接收图片流
    }
}

 

转载于:https://www.cnblogs.com/huangkaka/p/9309401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值