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. UI5-技术篇-Navigation And Routing

    主要记录下Router设置过程中出现的几个问题 1.View 首页设置 controlId 2.Manifest设置 2.1设置启动页 2.2设置默认配置 2.3设置Targets 首页设置 子页设置 ...

  2. phpstom激活

    phpstom官网:https://www.jetbrains.com/phpstorm/download 激活方法:激活时选择License server 填入http://idea.imsxm.c ...

  3. 第十三篇:socket网络编程

    本篇主要介绍网络编程的基础,以及UDP/TCP网络的socket编程,关于UDP套接字聊天器的实现.以及基于TCP套接字的服务器/客户端的实现上传下载功能. 一.网络通信 关于网络通信即通过网络(介质 ...

  4. git使用——远程仓库(Remote repositories)

    前言 为了能在任意 Git 项目上协作,你需要知道如何管理自己的远程仓库. 远程仓库是指托管在因特网或其他网络中的你的项目的版本库. 你可以有好几个远程仓库,通常有些仓库对你只读,有些则可以读写. 与 ...

  5. charles 主界面总结

    本文参考:charles 主界面总结 charles 主界面的介绍 Charles 主要提供两种查看封包的视图,分别名为 Structure Structure/结构视图,将网络请求按访问的域名分类, ...

  6. IDEA实用教程(五)——配置IDEA的JVM内存值

    ---恢复内容开始--- 四. 配置IDEA的JVM内存值 IDEA默认配置的JVM内存值比较低,如果硬件配置较高,可以修改该设置. 该设置需要在工程界面进行. 该操作仅建议内存8G以上,64位操作系 ...

  7. maya 在 pymel 中运行 mel

    maya 在 pymel 中运行 mel 前言 maya mel 自身定义了很多有用的方法,当我们用 pymel 开发的时候,不想重新写一遍 mel 已经有的功能,那么就可以在 pymel 中运行 m ...

  8. Destoon二开必看执行流程

    <?php 代码首先包含common.inc.php文件 在common.inc.php文件中,首先定义常量. define('IN_DESTOON', true); define('IN_AD ...

  9. el-input 只能输入数字并限制长度

    在上一个博客中,有关于限制长度的使用,本文介绍限制只能输入数字的方法 el-input 代码如下: <el-form-item label="账号" required> ...

  10. H5--性能测试(PageSpeed Insights )

    中文网站(不需要翻墙): http://www.googlespeed.cn 主要可实现: 1.测试手机与电脑打开的速度对比. 2.详细的测试结果 3.直观的统计数据,查看页面的共xx个请求.总共大小 ...