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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM