HttpClient模拟客户端请求实例
HttpClient Get请求:
/// <summary>
/// Get请求模拟
/// </summary>
/// <param name="url">请求URL</param>
public void HttpRequest(string url)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Task<HttpResponseMessage> response = client.GetAsync(url);
HttpResponseMessage result = response.Result;
this.queryResultPane.Text = result.Content.ReadAsStringAsync().Result;
}
HttpClient Post请求:
var aaa = new
{
Code = "139357a4-b38c-483e-a530-8f044a3dfe1c",
WechatOpenID = "33265198",
Area = "ShangHai",
Birthday = DateTime.Parse("1986-8-18"),
Gender = "male",
Level = 80,
Name = "Lynn",
PhoneNumber = "13129623023",
EmailType = "qq",
IsHaveParent = "no",
Province = "河南省",
TheCity = "郑州市",
//Age = 100,
Labels = new List<LabelEntity>() { new LabelEntity() { Label = "uuuu" }, new LabelEntity() { Label = "yyyy" } }
};
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//简单类型的参数,webApi方法里可以不定义参数,通过HttpContext.Current.Request.QueryString["Mobile"]来获取
Task<HttpResponseMessage> response =
//client.PostAsJsonAsync<ThreeMMember>(string.Format(U8688 + "MemberPoint/UpdateMemberInfo"), member);
client.PostAsJsonAsync(string.Format(U8688 + "MemberPoint/SaveMember"), aaa);
HttpResponseMessage result = response.Result;
this.Response.Output.Write(result.Content.ReadAsStringAsync().Result);
转一篇关于HttpClient的文章:
This tutorial shows how to call a web API from a .NET application, using HttpClient.
In this tutorial, we will write an app that consumes the following web API.
| Action | HTTP method | Relative URI |
|---|---|---|
| Get a product by ID | GET | /api/products/id |
| Create a new product | POST | /api/products |
| Update a product | PUT | /api/products/id |
| Delete a product | DELETE | /api/products/id |
To learn how to implement this API on the server, using ASP.NET Web API, see Creating a Web API that Supports CRUD Operations.
For simplicity, the client application in this tutorial is a Windows console application. HttpClient is also supported for Windows Phone and Windows Store apps. For more information, see Writing Web API Client Code for Multiple Platforms Using Portable Libraries
Create the Console Application
Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.
In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Windows. In the list of project templates, select Console Application. Name the project and click OK.
Install the Web API Client Libraries
Use NuGet Package Manager to install the Web API Client Libraries package.
From the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Client
Add the Model Class
Add the following class to the application:
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
This class matches the data model used in the "ProductStore" Web API project.
Create and Initialize HttpClient
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks; namespace ProductStoreClient
{
class Program
{
static void Main()
{
RunAsync().Wait();
} static async Task RunAsync()
{
using (var client = new HttpClient())
{
// TODO - Send HTTP requests
}
}
}
}
Notice that the Main function calls an async method named RunAsync and then blocks until RunAsyncc completes. Many of the HttpClient methods are async, because they perform network I/O. In the RunAsync method, I'll show the correct way to invoke those methods asynchronously. It's OK to block the main thread in a console application, but in a GUI application, you should never block the UI thread.
The using statement creates an HttpClient instance and disposes it when the instance goes out of scope. Inside the using statement, add the following code:
using (var client = new HttpClient())
{
// New code:
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
This code sets the base URI for HTTP requests, and sets the Accept header to "application/json", which tells the server to send data in JSON format.
Getting a Resource (HTTP GET)
The following code sends a GET request for a product:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync>Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
The GetAsync method sends the HTTP GET request. The method is asynchronous, because it performs network I/O. The await keyword suspends execution until the asynchronous method completes. When the method completes, it returns an HttpResponseMessage that contains the HTTP response.
If the status code in the response is a success code, the response body contains the JSON representation of a product. Call ReadAsAsync to deserialize the JSON payload to a Product instance. The ReadAsync method is asynchronous because the response body can be arbitrarily large.
A note about error handling: HttpClient does not throw an exception when the HTTP response contains an error code. Instead, the IsSuccessStatusCode property is false if the status is an error code.
If you prefer to treat HTTP error codes as exceptions, call the EnsureSuccessStatusCode method. This method throws an exception if the response status is not a success code:
try
{
HttpResponseMessage response = await client.GetAsync("api/products/1");
resp.EnsureSuccessStatusCode(); // Throw if not a success code. // ...
}
catch (HttpRequestException e)
{
// Handle exception.
}
HttpClient can can throw exceptions for other reasons as well — for example, if the request times out.
Using Media-Type Formatters in ReadAsync
When ReadAsAsync is called with no parameters, the method uses the default set of media-type formatters to read the response body. The default formatters support JSON, XML, and Form-url-encoded data.
You can also specify a list of formatters, which is useful if you have a custom media-type formatter:
var formatters = new List<MediaTypeFormatter>() {
new MyCustomFormatter(),
new JsonMediaTypeFormatter(),
new XmlMediaTypeFormatter()
};
resp.Content.ReadAsAsync<IEnumerable<Product>>(formatters);
Creating a Resource (HTTP POST)
The following code sends a POST request that contains a Product instance in JSON format:
// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri gizmoUrl = response.Headers.Location;
}
The PostAsJsonAsync method serializes an object to JSON and then sends the JSON payload in a POST request. To send XML, use the PostAsXmlAsync method. To use another formatter, call PostAsync:
MediaTypeFormatter formatter = new MyCustomFormatter();
response = await client.PostAsync("api/products", gizmo, formatter);
Updating a Resource (HTTP PUT)
The following code sends a PUT request to update a product.
// HTTP PUT
gizmo.Price = 80; // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
The PutAsJsonAsync method works like PostAsJsonAsync, except that it sends a PUT request instead of POST.
Deleting a Resource (HTTP DELETE)
The following code sends a DELETE request to delete a product.
// HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);
Like GET, a DELETE request does not have a request body, so you don't need to specify JSON or XML format.
Complete Code Example
Here is the complete code for this tutorial. The code is very simple and doesn't show error handling, but it shows the basic CRUD operations using HttpClient.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks; namespace ProductStoreClient
{
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
} class Program
{
static void Main()
{
RunAsync().Wait();
} static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
} // HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
Uri gizmoUrl = response.Headers.Location; // HTTP PUT
gizmo.Price = 80; // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo); // HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);
}
}
}
}
}
HttpClient模拟客户端请求实例的更多相关文章
- 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView
本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...
- 使用httpClient模拟http请求
在很多场景下都需要用到java代码来发送http请求:如和短信后台接口的数据发送,发送数据到微信后台接口中: 这里以apache下的httpClient类来模拟http请求:以get和Post请求为例 ...
- HttpClientUtil [使用apache httpclient模拟http请求]
基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...
- Node.js创建服务器和模拟客户端请求
1. 何为服务器 服务器是某种长期运行,等待请求资源的应用程序 2. 常见Web应用架构 3. 如何创建web服务器 Web服务器是使用HTTP协议,等待客户端连接后请求资源的驻守应用程序:HTTP协 ...
- 关于HttpClient模拟浏览器请求的參数乱码问题解决方式
转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...
- HttpClient模拟http请求
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- httpclient模拟服务器请求
// 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost Ht ...
- httpclient模拟post请求json封装表单数据
好长时间不更博了,主要肚子里没什么好墨水,哈哈.废话不说上代码. public static String httpPostWithJSON(String url) throws Exception ...
- java模拟post请求发送json
java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...
随机推荐
- base 64 编解码器
base 64 编解码 1. base64的编码都是按字符串长度,以每3个8bit的字符为一组, 2. 然后针对每组.首先获取每一个字符的ASCII编码. 3. 然后将ASCII编码转换成8bit的二 ...
- Amazon SQS简单介绍 上篇
SQS即Simple Queue Service, 是一个分布式的消息队列服务,使用它很easy,消息队列服务能够用来buffer burst, 使整个服务异步处理,不要求组件始终可用. 开发者最初使 ...
- NVIDIA+关联2015写学校招收评论(嵌入式方向,上海)
我没有写很长一段时间Blog中的一个,在过去的几个月中还没有看到太多的生长技术,来来回回一直在做的事情,要毕业找工作,但发现并没有冷静下来,准备过.这不是让人觉得暂时补习班是凡人啊. 本科不试试.那你 ...
- jQuery整理笔记9----函数形式发展
在一些照片中使用演示样本.插入.样式文件下载:点我进入下载 过去在开发过程中关于table方面的jquery应用不过局限于使用jquery操作table添加一行.删除一列等等操作.今天整理的跟过去用的 ...
- SystemTrayDemo
遗留问题:win7 java.awt.TrayIcon的displayMessage方法没有生效,通知消息不能正常弹出. 许多桌面环境都有一个区域用于放置在后台运行的程序的图标,这些程序偶尔会将某些 ...
- C#中的动态特性
众所周知,C#和Java一样,都是一门静态语言.在C# 4.0之前,想要和动态语言(诸如Python.Javascript等)进行方便地互操作是一件不太容易的事情.而C# 4.0为我们带来的dynam ...
- MTK MOTA升级步骤
MOTA的前提下有其自己的server,MTK我在已经完成,可以MTK应用,然后移动到它自己的server向上. 1.打开ProjectConfig.mk中间MTK_SYSTEM_UPDATE_SUP ...
- uva10954 - Add All(multiset功能)
题目:10954 - Add All 题目大意:求n个数的和,可是有点不一样的是题目要求计算最少花费.每次两个数相加,得到的那个数就是每次计算的cost. 解题思路:之前没有想到用multiset,自 ...
- HDU ACM 1290 献给杭电五十周年校庆的礼物
解析: 1.n条直线把平面切割成的区域数为: f(n)=f(n-1)+n=n(n+1)/2+1; 2.把空间切割为最多区域数的时候,第n个平面与前(n-1)个平面相交.且无三面共线,因此该平面与前(n ...
- PHP与EXCEL PHPExcel
1.PHPExcel一个简短的引论 PHPExcel 它是用来操作Office Excel 文档PHP图书馆,它是基于微软的OpenXML标准PHP语言.能够使用它来读.写不同格电子表的类型格,例如 ...