本文使用.net core后端接口程序,实现向一个接口提交一个json数据,再从接口取到一个json数据。
post访问方法
public static string HttpPost(string url, string param = null)
{
HttpWebRequest request;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Timeout = 15000;
request.AllowAutoRedirect = false;
StreamWriter requestStream = null;
WebResponse response = null;
string responseStr = null;
try
{
requestStream = new StreamWriter(request.GetRequestStream());
requestStream.Write(param);
requestStream.Close();
response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception ex)
{
responseStr = ex.Message + ";" + ex.StackTrace;
}
finally
{
request = null;
requestStream = null;
response = null;
}
return responseStr;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
调用取值格式化
GetByAttrDto b = new GetByAttrDto();
b.attrName = attrName;
b.attrValue = attrValue;
b.className = className;
string jsonParam = JsonConvert.SerializeObject(b);
var responseString = HttpPost(_url,jsonParam);
var json = (JObject)JsonConvert.DeserializeObject(responseString);
然后是用json[“code”]这种格式读取依次赋值就行了,但是不能直接返回json,否则json的值默认折叠,显示不出来,需要依次读取出来再返回。