其实调用接口post数据的方法都差不多,区别无非就是格式不一样,编码不一样
过程大致如下:
1.设置HttpWebRequest请求,封装头部和编码格式
2.将提交的内容转换为byte字节,写入到请求流里面
3.发送POST数据请求服务器
4.接收服务器返回信息,从返回的响应流里面读出结果
XML提交方法:输入的参数需要先转换为xml格式的字符串
/// <summary>
/// 接口调用方法,XML格式
/// </summary>
/// <param name="url">接口地址</param>
/// <param name="param">参数xml格式的字符串</param>
/// <returns></returns>
public static string WebRequestPost(string url, string param)
{
string strResult = "";
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream stream = null;
StreamReader reader = null;
try
{
request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.KeepAlive = true;
request.Timeout = 100 * 1000;
request.ContentType = "text/xml";
//把数组转换成流中所需字节数组类型
byte[] bytes = Encoding.UTF8.GetBytes(param);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();//释放
//发送POST数据请求服务器
response = (HttpWebResponse)request.GetResponse();
Encoding encoding = Encoding.UTF8;
if (!string.IsNullOrEmpty(response.CharacterSet))
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
//获取服务器返回信息
stream = response.GetResponseStream();
reader = new StreamReader(stream, encoding);
strResult = reader.ReadToEnd();
}
catch (WebException we)
{
using (var stream1 = we.Response.GetResponseStream())
using (var reader1 = new StreamReader(stream1))
{
var data = reader1.ReadToEnd();
throw new Exception(data);
}
}
finally
{
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (response != null) response.Close();
}
return strResult;
}
JSON提交方法:输入的参数需要先转换为json格式字符串
/// <summary>
/// 接口调用方法,JSON格式
/// </summary>
/// <param name="url"></param>
/// <param name="jsonData">参数是{"key1": value1, "key2": value2}格式的json数据</param>
/// <returns></returns>
public static string PostData(string url, string jsonData)
{
string result = "";
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = 100 * 1000;//设置请求超时时间,单位为毫秒
request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(jsonData);
request.ContentLength = data.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
catch (WebException we)
{
using (var stream1 = we.Response.GetResponseStream())
using (var reader1 = new StreamReader(stream1))
{
var data = reader1.ReadToEnd();
throw new Exception(data);
}
}
finally
{
if (response != null) response.Close();
}
return result;
}