get、post方法请求接口,测试方法
2019-08-12 本文已影响0人
孤傲小狼
private static string url = "https://localhost:44317/api/";
public static string PostRequestAPI(string apiName, Dictionary<string, object> parameters)
{
//实例化
WebClient client = new WebClient();
//地址
string requestUrl = url + apiName;
//数据较大的参数
string datastr = "";
foreach (var item in parameters)
{
datastr += item.Key + "=" + item.Value + "&";
}
datastr = datastr.Substring(0, datastr.Length - 1);
//参数转流
byte[] bytearray = Encoding.UTF8.GetBytes(datastr);
string myParameters = "key=" + "123" + "&system_id=" + "123" + "";
byte[] aaddd = Encoding.UTF8.GetBytes(myParameters);
//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//长度
client.Headers.Add("ContentLength", bytearray.Length.ToString());
//上传,post方式,并接收返回数据(这是同步,需要等待接收返回值)
byte[] responseData = client.UploadData(requestUrl, aaddd);
//释放
client.Dispose();
//处理返回数据(一般用json)
string srcString = Encoding.UTF8.GetString(responseData);
return srcString;
}
public class use
{
public string name { get; set; }
public string sex { get; set; }
}
/// <summary>
/// Get方式请求接口
/// </summary>
/// <param name="apiNamespace"></param>
/// <param name="apiName"></param>
/// <param name="parameters"></param>
public static string GetRequestAPI(string apiNamespace, string apiName, Dictionary<string, object> parameters)
{
//地址
//string url = "https://gw.open.1688.com/openapi/param2/1/" + apiNamespace + "/" + apiName + "/";// + StaticInfo.AppKey + "?";
string url = "http://192.168.2.237/api/" + apiNamespace + "/" + apiName + "?";
foreach (var item in parameters)
{
url += item.Key + "=" + item.Value + "&";
}
url = url.Substring(0, url.Length - 1);
//实例化
WebClient client = new WebClient();
//上传并接收数据
Byte[] responseData = client.DownloadData(url);
//接收返回的json的流数据,并转码
string result = Encoding.UTF8.GetString(responseData);
return result;
}
/// <summary>
/// Get方式请求接口
/// </summary>
/// <param name="url">请求地址</param>
/// <returns></returns>
public static string GetRequestAPI(string url)
{
//实例化
WebClient client = new WebClient();
//上传并接收数据
Byte[] responseData = client.DownloadData(url);
//接收返回的json的流数据,并转码
string result = Encoding.UTF8.GetString(responseData);
return result;
}