如何像Postman一样模拟Ajax调用?

时间:2016-04-25 21:14:31

标签: jquery json ajax postman

我使用Postman从网址获取json数据。结果很好,我有一个数组作为json字符串。以下是我在使用Postman获取数据时捕获的图像:

Header

Body

我想在Ajax调用中执行此操作,但不知道如何实现它。这是我尝试过的一个例子:

function getDeliveryStatusDetail(qrcode) {
var url = 'http://thecompany.com/DeliverStatusDetail/DeliverStatusDetail';
var data = JSON.stringify({ QRCode: qrcode });
$.ajax
  ({
      type: "POST",
      url: url,
      dataType: 'jsonp',
      async: false,
      data: data,
      contentType: "application/json; charset=utf-8",
      beforeSend: function (xhr) {
          xhr.setRequestHeader('Authorization', 'lgGbkiJ1n2RtjaXLHzvHs7yejzejt+0O4ELj7im8PzYGAOyTO');
      },
      success: function () {
          alert('Thanks for your comment!');
      },
      error: function (xhr, status, error) {
          alert(xhr.responseText);
      }
      });
}

成功返回json看起来像这样:

    {
  "QRCode": "KLO00998",
  "ReceiverAddress": {
    "FullName": "Elizabeth Jerah"
  },
  "QRCodeDetail": [
    {
      "QRCode": "KLO00998",
      "Status": "A"
    },
    {
      "QRCode": "KLO00998",
      "Status": "T"
    },
    {
      "QRCode": "KLO00998",
      "Status": "B"
    },
    {
      "QRCode": "KLO00998",
      "Status": "C"
      "SignatureReturn": ""
    }
  ],
  "code": "100",
  "desc": "Success",
  "ErrorMessages": null,
  "ValidationMessages": null

    }

上面的代码可以模拟Postman的过程,但不成功。你能帮我重新格式化示例代码吗?

1 个答案:

答案 0 :(得分:4)

最后,我在C#中推出了一个新的解决方案。事件我的问题与C#无关,但这是解决此问题的唯一解决方案。

 var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://mycompany.com/DeliverStatusDetail/DeliverStatusDetail");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers["Authorization"] = "Alpha lgGbkiJ1n2RtjaXLHzvHs7yejzejt+0O4";

            using (var streamWriter = new System.IO.StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"QRCode\":\"HS2016000\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                Label1.Text = result;
            }

我打算在客户端调用ajax,但是像我在问题中描述的那样陷入困境。然后我在服务器端通过在C#中建立一个HttpWebRequest来尝试它,并且可以在ASPx页面中运行代码后得到结果。