使用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 ...
随机推荐
- [转]大牛们是怎么阅读 Android 系统源码的
转自:http://www.zhihu.com/question/19759722 由于工作需要大量修改framework代码, 在AOSP(Android Open Source Project)源 ...
- Nginx 之 Rewrite 规则
write 规则介绍 Rewite 规则作用 Rewrite规则可以实现对url的重写,以及重定向 作用场景: URL访问跳转,支持开发设计,如页面跳转,兼容性支持,展示效果等 SEO优化 维护:后台 ...
- Vue使用ref 属性来获取DOM
注意,在父组件中可以使用this.$refs.属性名 获取任何元素的属性和方法,子组件不可以获取父组件中的 <!DOCTYPE html> <html lang="en& ...
- vue---父调子 $refs (把父组件的数据传给子组件)
ps:App.vue 父组件 Hello.vue 子组件 App.vue : <template> <div id="app"> <input t ...
- CommandLineParse类(命令行解析类)
https://blog.csdn.net/jkhere/article/details/8674019 https://sophia0130.github.io/2018/05/08/Command ...
- Java中的经典算法之快速排序(Quick Sort)
Java中的经典算法之快速排序(Quick Sort) 快速排序的思想 基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小, 然后再按此方法对 ...
- P1736 创意吃鱼法[二维dp]
题目背景 感谢@throusea 贡献的两组数据 题目描述 回到家中的猫猫把三桶鱼全部转移到了她那长方形大池子中,然后开始思考:到底要以何种方法吃鱼呢(猫猫就是这么可爱,吃鱼也要想好吃法 ^_*).她 ...
- go语言-关于文件的操作和解释
一.文件存放的位置 bin文件:存放编译后的二进制文件 pkg文件:存放编译后的库文件 src文件:存放源代码文件 二.运行文件的常用命令 两种运行区别(直接运行和编译后运行) 1.编译生成可执行文件 ...
- js中event.preventDefault()和 event.stopPropagation( ) 方法详解
event.preventDefault() 1.首先event.preventDefault()是通知浏览器不要执行与事件关联的默认动作,例如: 这里a标签的默认事件是跳转,这里我们告诉浏览器取消 ...
- LightOJ - 1148-Mad Counting (数学)
链接: https://vjudge.net/problem/LightOJ-1148 题意: Mob was hijacked by the mayor of the Town "Trut ...