使用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 ...
随机推荐
- Modelsim问题集锦
前言 收集工程调试中遇到的modelsim问题. 问题 (1)仿真发现时钟信号和理论上的数据信号没有边沿对齐. 解决:一般是时钟精度不匹配的问题. 如果想要1ns的精度则代码中的精度需设置为: v语法 ...
- S3C2440 gpio
WATCHDOG TIMER 原理图 手册 举例 start.S .globl _start _start: /* 关看门狗 */ /* 往WTCON(0x53000000)写0 */ ldr r0, ...
- djangoNotes
学员管理 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...
- django2以后的版本Foreignkey的变动
目录 class User(AbstractUser): """用户表""" job = models.ManyToManyField(to ...
- Python函数Day1
一.函数的初识 函数的定义:函数最主要的目的是封装一个功能,一个函数就是一个功能 定义函数的格式: def 函数名(): 函数体 def my_len(): count = 0 s1 = 'hahah ...
- 使用框架时,在web.xml中配置servlet时,拦截请求/和/*的区别。
关于servlet的拦截设置,之前看了好多,说的都不太清除,明白. 最近明白了一些,总的来说就是保证拦截所有用户请求的同时,放行静态资源. 现整理如下: 一.我们都知道在基于Spring的Applic ...
- No qualifying bean of type 'org.springframework.scheduling.TaskScheduler' available
2019-07-22 17:59:30,966 [DEBUG] [localhost-startStop-1] [ScheduledAnnotationBeanPostProcessor.java : ...
- 2020年日期表-python实现
import pandas as pdimport calendarimport datetime # 生成日期范围date = pd.date_range("2020-01-01" ...
- 关于Mybatis查询结果的封装
1.结果封装为List<Object> 接口示例: public List<Members> selectMembersListByName(String name); 配置文 ...
- 物联网之窄带物联网(NB-IOT)
NB-IoT即窄带物联网(Narrow Band Internet of Things),NB-IOT构建在蜂窝网络之上,只消耗大约180KHZ的带宽,可直接部署于GSM(2G).UMTS(3G).L ...