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端示例的更多相关文章

  1. Java之HttpClient调用WebService接口发送短信源码实战

    摘要 Java之HttpClient调用WebService接口发送短信源码实战 一:接口文档 二:WSDL 三:HttpClient方法 HttpClient方法一 HttpClient方法二 Ht ...

  2. httpclient调用webservice接口的方法实例

    这几天在写webservice接口,其他的调用方式要生成客户端代码,比较麻烦,不够灵活,今天学习了一下httpclient调用ws的方式,感觉很实用,话不多说,上代码 http://testhcm.y ...

  3. 使用HttpClient调用第三方接口

    最近项目中需要调用第三方的Http接口,这里我用到了HttpClient. 首先我们要搞明白第三方接口中需要我们传递哪些参数.数据,搞明白参数以后我们就可以使用HttpClient调用接口了. 1.调 ...

  4. HttpClient调用RestFul接口(post和get方式)

    /** * @version V1.0 * @Description 调用http接口工具类 * @Author pc * @Date 2018/3/2 11:03 */public class Ht ...

  5. SpringMVC 结合HttpClient调用第三方接口实现

    使用HttpClient 依赖jar包 1:commons-httpclient-3.0.jar 2:commons-logging-1.1.1.jar 3:commons-codec-1.6.jar ...

  6. java 通过httpclient调用https 的webapi

    java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口, ...

  7. Java调用Http/Https接口(4)--HttpClient调用Http/Https接口

    HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似.文中所使用到的软件版本:Java 1.8. ...

  8. 使用httpClient 调用get,Post接口

    1.httpClient 调用get接口 private async Task<IList<(int columnId, string columnName)>> GetFun ...

  9. httpClient调用接口的时候,解析返回报文内容

    比如我httpclient调用的接口返回的格式是这样的: 一:data里是个对象 { "code": 200, "message": "执行成功&qu ...

  10. 使用httpclient异步调用WebAPI接口

    最近的工作需要使用Bot Framework调用原有的WebAPI查询数据,查找了一些方法,大部分都是使用HttpClient调用的,现时贴出代码供参考 using System; using Sys ...

随机推荐

  1. iOS动画:CAKeyframeAnimation

    网络中Core Animation类的继承关系图       属性简介 @interface CAKeyframeAnimation : CAPropertyAnimation /* 提供关键帧数据的 ...

  2. View Controller Programming Guid for iOS 笔记

    1.View Controller 基础 1.1 View Controller 分类 ViewController分为container view controller 和content view ...

  3. iOS开发微信支付的介绍与实现

    1.前期准备 1) 到微信开放平台注册账号 需要登录邮箱验证 填写您的商户信息 2) 进入管理中心 --- 移动应用 --- 创建移动应用 --- 根据页面完善应用资料 3) 审核过后,通过应用详情页 ...

  4. 基于数组的shell脚本编写

    基于数组的shell脚本编写 2017年08月17日 22:56:36 momokuku123 阅读数:369 数据:变量,文件,数组 变量:存储单个元素的内存中的一块存储空间 数组:存储多个元素的内 ...

  5. Powershell-获取Hyper-V复制状态

    Get-VM | Select-Object name,ReplicationHealth

  6. 用js刷剑指offer(栈的压入、弹出序列)

    题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序.假设压入栈的所有数字均不相等.例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压 ...

  7. GPU---NVIDIA GPU 计算能力

    查询网址:https://developer.nvidia.com/cuda-gpus 使用,makefile文件实例: GPU= CUDNN= OPENCV= OPENMP= DEBUG= ARCH ...

  8. java基础(1)----简介

    基础语法. 面向对象. 字符串和集合. IO流. 接口. lambda. 方法引用. Stream. 模块化. 一.java的前世今生: J2SE:标准体验版.J2EE:企业版.J2ME:小型版(移动 ...

  9. Android中sp和px之间关系探究

    记得当时在刚接触Android时都在说不要用px,要用sp,所以在实际工作当中当然就按照这个规则,所以都要将px换算成sp,而我在实际工作中的换算规则是dp=px * 1.5,而且用这种规则到现在基本 ...

  10. jmeter接口测试json详解

    本篇围绕jmeter(压力测试工具),请求json与返回json串处理进行解析,初入测试,理解如有不对的地方请大家及时提点~~ 在这里jmeter工具的使用不在做解释 首先说下乱码问题,在这里无脑5步 ...