URL类型入参串调用接口

  最近通过调用另一个合作公司提供的接口实现方法,借鉴同事之前编写的方法

  Models.JSON.Patient类中有各种属性,也可增加属性来满足新需求

public string TakeAppoint(string AppointCode, string RefundAmount, string BusinessSource)
{
  try
  {
    //调用地址
    string strUrl = UrlSet.Default.UrlTakeAppoint;
    //将参数赋入地址
    strUrl = string.Format(strUrl, AppointCode, RefundAmount, BusinessSource);
    //调用web
    string returnValue = Analytical.Invoke(strUrl);
    //解析返回值
    Models.JSON.Patient patient = Analytical.AnalyticalJson(returnValue);
    if (Analytical.errCode < 1)
    {
    this.errCode = Analytical.errCode;
    this.errMsg = Analytical.errMsg;
    return "-1|" + Analytical.errMsg;
    }
    return "1|" + AppointCode + "|" + RefundAmount + "|" + BusinessSource;
    }
  catch (Exception ex)
  {
    this.errCode = -1;
    this.errMsg = ex.Message + ex.StackTrace;
    Logger.WriteLog(errMsg, true);
    return "-1|" + errMsg;
  }
}

 下面的方法可以从返回的URL串中获取需要的参数

public static string Invoke(string strUrl)
{
  string returnValue = string.Empty;

  try
  {
    Logger.FolderName = "CAREATE";
    Logger.WriteLog(string.Format(Logger.ProcessHISMessageFormat, "入参", strUrl, "", ""), false);

    // 调用接口
    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
    System.IO.StreamReader streamRead = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
    returnValue = streamRead.ReadToEnd();
    streamRead.Close();

    Logger.FolderName = "CAREATE";
    Logger.WriteLog(string.Format(Logger.ProcessHISMessageFormat, "出参", strUrl, returnValue, ""), false);

    return returnValue;
  }
  catch (Exception ex)
  {
    return returnValue;
  }
}

 解析返回值,赋入Models.JSON.Patient实体中

public static Models.JSON.Patient AnalyticalJson(string returnValue)
{
  Models.JSON.Patient patient = new Models.JSON.Patient();

  if (string.IsNullOrEmpty(returnValue))
  {
    errCode = -1;
    errMsg = "未获取到数据!";
    return patient;
  }

  // 取result值
  JObject jsMessage = JObject.Parse(returnValue);
  string returnCode = (string)jsMessage["result"];

  if (returnCode == "-1")
  {
    errCode = -1;
    errMsg = (string)jsMessage["message"];
    return null;
  }

  // 解析返回值编码
  string msg = AnalyticalCode(returnCode);
  if (!string.IsNullOrEmpty(msg))
  {
    errCode = -1;
    errMsg = msg;
    return patient;
  }

  // 返回数据行数
  int rows = Convert.ToInt32(jsMessage["data"]["total"].ToString());
  if (rows < 0)
  {
    errCode = -1;
    errMsg = "未获取到数据!";
    return patient;
  }

  JArray jar = JArray.Parse(jsMessage["data"]["rows"].ToString());

  patient = Deserialize<Models.JSON.Patient>(jar[0].ToString());

  errCode = 1;
  return patient;
}

原文地址:https://www.cnblogs.com/yupeiyuan/p/5060486.html