使用HttpClient调用WebAPI接口,含WebAPI端示例
API端:
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http; namespace WebApi.Controllers
{
public class DefaultController : ApiController
{
private ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
IList<menu> List = new List<menu>(); public DefaultController()
{
for (int i = ; i <= ; i++)
{
List.Add(new menu { menuId = i, menuName = "Menu" + i });
}
} // GET: api/Default
public IEnumerable<menu> Get()
{
return List;
} // GET: api/Default/5
public menu Get(int id)
{
try
{
return List.FirstOrDefault(m => m.menuId == id);
}
catch(Exception e)
{
return new menu();
}
} // POST: api/Default
//public void Post(int id,[FromBody]menu menu)
//{
// log.Info(menu.menuName);
//} // PUT: api/Default/5
public void Put(int id, string guid, [FromBody]string value)
{
log.InfoFormat("PUT id:{0},value:{1},guid:{2}", id, value, guid);
} // DELETE: api/Default/5
public void Delete(int id)
{
log.Info(id);
} public IHttpActionResult UploadFile()
{
//log.Info(id);
log.Info(HttpContext.Current.Request.Form["qq"]);
var file = HttpContext.Current.Request.Files[];
file.SaveAs(HttpContext.Current.Server.MapPath("/test.jpg"));
return Ok<string>("test");
}
} public class menu
{
public int menuId { get; set; }
public string menuName { get; set; }
}
}
调用端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Text;
using System.Net.Http.Headers;
using System.IO;
using Newtonsoft.Json; namespace WebApi.Controllers
{
public class ClientController : Controller
{
// GET: Client
public ActionResult Index()
{ //HttpClient client = new HttpClient();
//string Url = "http://localhost:33495/api/default/"; #region 原始方式调用
//StringContent方式调用
//var result = client.PostAsync(Url, new StringContent("111", Encoding.UTF8, "application/json")).Result; //ByteArrayContent方式
//var data = Encoding.UTF8.GetBytes("\"ddd\"");
//data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new menu { menuId = 1, menuName = "33333" }));
//data = Encoding.UTF8.GetBytes("{menuId:1,menuName:333}");
//var content = new ByteArrayContent(data);
//content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
//var result_byte = client.PostAsync(Url, content).Result; //PostAsJsonAsync方式
//client.PostAsJsonAsync(Url, "ss");
#endregion #region 多参数传参
//client.PutAsJsonAsync(string.Format("{0}{1}?guid={2}", Url, 5, Guid.NewGuid()), "test");
#endregion #region 服务端上传图片
//服务端上传图片
//using (HttpClient client = new HttpClient())
//{
// var content = new MultipartFormDataContent();
// //添加字符串参数,参数名为qq
// content.Add(new StringContent("123456"), "qq"); // string path = Server.MapPath("/Images/test.jpg");
// //添加文件参数,参数名为files,文件名为123.png
// content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "test.jpg"); // var requestUri = "http://localhost:33495/api/default/";
// var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result; // Response.Write(result);
//}
#endregion return null;
} public ActionResult HTML()
{
return View();
} public ActionResult Upload()
{
return View();
}
}
}
HTML(AJAX上传)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>webapi上传图片</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
</head>
<body>
<h2>webapi create</h2>
<div>
<form name="form1" method="post" enctype="multipart/form-data">
<div>
<label for="image1">Image</label>
<input type="text" name="test" id="test" />
</div>
<div>
<label for="image1">Image</label>
<input type="file" name="photo" id="photo" />
</div>
<div>
<input type="button" value="ajax upload" id="btnUpload" />
</div>
<div>
<img id="phptoPic" width="" />
</div>
</form>
</div>
<script type="text/javascript">
$(function () {
$("#btnUpload").click(function () {
var formData = new FormData();
formData.append("photo", $("#photo")[].files[]);
$.ajax({
url: '/api/default/UploadFile',
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function (res) {
//console.log(res);
if (res == "test") {
$("#phptoPic").attr("src", res.url)
} else {
alert(res.message)
}
}
})
})
})
</script>
</body>
</html>
微软官网示例:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Product App</title>
</head>
<body> <div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div> <script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
var uri = '/api/Default'; $(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
});
}); function formatItem(item) {
return item.menuId + item.menuName;
} function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
</body>
</html>
使用HttpClient调用WebAPI接口,含WebAPI端示例的更多相关文章
- Java之HttpClient调用WebService接口发送短信源码实战
摘要 Java之HttpClient调用WebService接口发送短信源码实战 一:接口文档 二:WSDL 三:HttpClient方法 HttpClient方法一 HttpClient方法二 Ht ...
- httpclient调用webservice接口的方法实例
这几天在写webservice接口,其他的调用方式要生成客户端代码,比较麻烦,不够灵活,今天学习了一下httpclient调用ws的方式,感觉很实用,话不多说,上代码 http://testhcm.y ...
- 使用HttpClient调用第三方接口
最近项目中需要调用第三方的Http接口,这里我用到了HttpClient. 首先我们要搞明白第三方接口中需要我们传递哪些参数.数据,搞明白参数以后我们就可以使用HttpClient调用接口了. 1.调 ...
- HttpClient调用RestFul接口(post和get方式)
/** * @version V1.0 * @Description 调用http接口工具类 * @Author pc * @Date 2018/3/2 11:03 */public class Ht ...
- SpringMVC 结合HttpClient调用第三方接口实现
使用HttpClient 依赖jar包 1:commons-httpclient-3.0.jar 2:commons-logging-1.1.1.jar 3:commons-codec-1.6.jar ...
- java 通过httpclient调用https 的webapi
java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口, ...
- Java调用Http/Https接口(4)--HttpClient调用Http/Https接口
HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似.文中所使用到的软件版本:Java 1.8. ...
- 使用httpClient 调用get,Post接口
1.httpClient 调用get接口 private async Task<IList<(int columnId, string columnName)>> GetFun ...
- httpClient调用接口的时候,解析返回报文内容
比如我httpclient调用的接口返回的格式是这样的: 一:data里是个对象 { "code": 200, "message": "执行成功&qu ...
- 使用httpclient异步调用WebAPI接口
最近的工作需要使用Bot Framework调用原有的WebAPI查询数据,查找了一些方法,大部分都是使用HttpClient调用的,现时贴出代码供参考 using System; using Sys ...
随机推荐
- 软件自带依赖库还是共享对象库/为什么linux发行版之间不能有一个统一的二进制软件包标准
接前文:Linux软件包(源码包和二进制包)及其区别和特点 在前文,我们知道了linux软件包分为源码包和二进制包两种方式,而不同的发行版之间又有着自己的二进制打包格式. 首先,软件运行依赖着各种各样 ...
- Android面试题 请解释下单线程模型中Message、Handler、MessageQueue、Looper之间的关系
简单的说,Handler获取当前线程中的looper对象,looper用来存放从MessageQueue中取出的Message,再由Handler进行Message分发和处理,按照先进先出执行. Me ...
- Java泛型全解析【接口、类、封装类型】
目录 1.导读 2.为何需要泛型? 3.泛型的定义格式 3.泛型的好处 4.什么时候使用泛型? 5.泛型的擦除 6.泛型的补偿 7.泛型的应用 7.1[泛型类] ...
- AD 复制状态检查
微软提供了一下工具进行AD复制状态检查 Repadmin: http://technet.microsoft.com/en-us/library/cc811551%28v=ws.10%29.asp ...
- 用js刷剑指offer(栈的压入、弹出序列)
题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序.假设压入栈的所有数字均不相等.例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压 ...
- 去除chrome网站https的安全检测
chrome://net-internals/#hsts 访问该网址,把要禁止检测的网址放在下面:
- 8 loader - 配置处理css样式表的第三方loader
// 使用import语法,导入css样式表 import './css/index.css' // 注意:webpack,默认只能打包处理JS类型的文件,无法处理其它的非JS类型的文件: // 如果 ...
- jQuery隐藏和显示从上往下的实现方法
jquery 显示隐藏方法实现动画效果 方向 显示 隐藏 左上角到右下角 show() hide() 垂直向下 slideDown() slideUp() 水平与垂直两个方向 toggle() 垂直向 ...
- JSOI2009 密码 和 JSOI2007 文本生成器 和 ZOJ3545 Rescue the Rabbit
密码 众所周知,密码在信息领域起到了不可估量的作用.对于普通的登陆口令,唯一的破解 方法就是暴力破解一逐个尝试所有可能的字母组合,但这是一项很耗时又容易被发现的工 作.所以,为了获取对方的登陆口令,在 ...
- Mybatis之动态SQL&OGNL表达式
1.接口 public interface MemberMapperDynamicSQL { public List<Members> selectMembersByIf(Members ...