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; }//用于接收图片流
}
}