最近参与了公司的一个和微信平台相关的项目,最近加班加点和第三方调接口。接口走的是http协议,对方返回数据格式为json格式。现在记录下用到的一些知识,以便以后方便查阅。c#真是方便,可以通过JavaScriptSerializer类实现对json数据转化为对象,将对象转化为json串
对方大概提供了两种类型的接口:
一种是直接访问url便可获得数据,一种是要我这边组织json格式的数据再post的过去。
1:
var request = WebRequest.CreateHttp(MSURI);//实例化HttpWebRequest对象
request.AllowAutoRedirect = true;//设置请求跟随重定向响应
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;//设置请求解压缩的类型
request.UserAgent = Util.UserAgent_Common;//设置用户客户端信息
request.Method = "POST";
//request.ContentType = "application/json";
var response = request.GetResponse();//生成响应对象
string content;
using (var reader = new StreamReader(response.GetResponseStream()))
{
content = reader.ReadToEnd();
}
Trace.WriteLine(content);
2:
string orderJson = Util.SharedJson.Value.Serialize(order);
Trace.WriteLine("json发送信息\r\n" + orderJson);
try
{
var request = WebRequest.CreateHttp(MSORDERURI + System.Web.HttpUtility.UrlEncode(orderJson, Encoding.UTF8));
Trace.WriteLine("请求地址:" + MSORDERURI + System.Web.HttpUtility.UrlEncode(orderJson, Encoding.UTF8));
request.AllowAutoRedirect = true;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.UserAgent = Util.UserAgent_Common;
request.Method = "POST";
//根据接口的要求对post过去的内容设置编码方式
using (var requestStream = request.GetRequestStream())
{
var jsonContent = new StringContent(orderJson, Encoding.UTF8);
request.ContentType = "application/json";
jsonContent.CopyToAsync(requestStream).Wait(500);
}
var response = request.GetResponse();
string content;
using (var reader = new StreamReader(response.GetResponseStream()))
{
content = reader.ReadToEnd();
}
Trace.WriteLine(content);