C#中请求接口代码,并将返回报文解析

工作中用到的,记录下!

//接口调用
private string InterfaceRequest(string url,string reqmsg,ref string errormsg)
{
  try
  {
    Logger.WriteLine("[TsCustomer][CustomerPortrait][InterfaceRequest] url={0},reqmsg={1},errormsg={2}",url,reqmsg,errormsg);
    //按照utf8进行编码
    Encoding enc = Encoding.UTF8;
    byte[] info = enc.GetBytes(reqmsg);
    //调用
    HttpWebRequest hwr=HttpWebRequest.Create(url) as HttpWebRequest;
    hwr.Timeout = 30000;//超时时间
    hwr.Method = "POST";//提交方式
    hwr.ContentType = "application/json";//请求类型
    hwr.UserAgent = "Interact AppServer";
    hwr.ContentLength = info.Length; //内容长度
    Stream st = hwr.GetRequestStream(); //获取请求流
    st.Write(info, 0, info.Length);
    st.Close();
    //读取结果,向接口发送请求
    HttpWebResponse response = hwr.GetResponse() as HttpWebResponse;
    StreamReader reader = new StreamReader(response.GetResponseStream(), enc);

    string respmsg = reader.ReadToEnd();
    reader.Close();
    Logger.WriteLine("[CustomerPortrait][InterfaceRequest] url=[{0}] recvmsg=[{1}]",url,respmsg);
    return respmsg;
  }
  catch(Exception ex)
  {
    LogBlockWriter lbw=Logger.BeginWriteBlock();
    lbw.WriteLine("[CustomerPortrait][InterfaceRequest]Exception");
    lbw.WriteLine(ex);
    Logger.EndWriteBlock(lbw);
    errormsg = ex.Message;
    return "";
  }
}

//respmsg 接口返回报文

//RecreationClubPresent_url 接口地址(接口地址是放在数据库里的,方便更改)

//errormsg (如果请求接口有错误,用来传递报错信息)

string respmsg = InterfaceRequest(RecreationClubPresent_url,reqmsg,ref errormsg);

//解析报文

private string PersonalCenterPresent_msgParse(string respmsg,string PersonalCenterPresent_url)
{
  DataRecordSet drs = new DataRecordSet();
  string errormsg="";
  try
  {

    //转换返回报文的数据类型
    JsonObject joret = JsonObject.Decode(respmsg);
    if (joret == null)
    {
      errormsg = "读取接口返回结果失败";
      Logger.WriteLine("[CustomerPortrait][GetPortrait] error:读取返回结果失败");
      drs.SetAttribute("result", errormsg);
      return drs.ToXmlDocument().OuterXml;
    }

    //获取报文中“header”节点的数据
    JsonObject header = joret["header"].ObjectValue();
    if(header["resMsg"].ToString().Length > 0 && !header["resMsg"].ToString().Equals("查询到数据"))

    {
      errormsg = header["resMsg"].ToString();
      drs.SetAttribute("result", errormsg);
      return drs.ToXmlDocument().OuterXml;
    }

    //body节点值
    JsonObject body = joret["body"].ObjectValue();
    if(body == null)
    {
      errormsg = "读取接口返回结果失败";
      Logger.WriteLine("[CustomerPortrait][GetPortrait] error:读取接口返回结果失败");
      drs.SetAttribute("result", errormsg);
      return drs.ToXmlDocument().OuterXml;
    }
     //获取"body"节点中的"physicalGifts"数组节点
    JsonKeyValue physicalGifts = body["physicalGifts"];

    if(physicalGifts != null && physicalGifts.ToString() != "")
    {  

      //physicalGifts转换类型
      ArrayList physicalGiftsList = physicalGifts.ArrayValue();
      if(physicalGiftsList.Count > 0)
      {

        //循环把数据取出转换成DataRecord类型
        for(int i = 0;i<physicalGiftsList.Count;i++)
        {
          DataRecord physicalGift = new DataRecord("physicalGift");
          JsonObject physicalGiftj = physicalGiftsList[i] as JsonObject;
          physicalGift.AddField("activityName",physicalGiftj["activityName"].ToString());
          physicalGift.AddField("giftName",physicalGiftj["giftName"].ToString());
          physicalGift.AddField("useDateStr",physicalGiftj["useDateStr"].ToString());
          drs.AddRecord(physicalGift);
        }
      }

  }

  catch(Exception ex)
  {
    LogBlockWriter lbw=Logger.BeginWriteBlock();
    lbw.WriteLine("[CustomerPortrait][PersonalCenterPresent_msgParse]Exception");
    lbw.WriteLine(ex);
    Logger.EndWriteBlock(lbw);
    drs.SetAttribute("result",":"+ex.Message);
  }
  return drs.ToXmlDocument().OuterXml;
}

我是代码搬运工!!!
原文地址:https://www.cnblogs.com/FanKL/p/13539760.html