如何在POST方法上从API获取数据

时间:2014-03-15 07:50:51

标签: asp.net api

我必须从API中获取一些数据。这个API只提到了这个方法。没有文档显示如何访问和all.Data将作为Json返回。

这是产品API

1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}

我已经生成了令牌,我试图像这样访问它。但没有收到任何东西。我找到了一个例子并试图这样做。可能这是错的。任何人都可以告诉我如何访问并获取data.Please请参阅下面的代码并感谢先进。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;



public partial class Products : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
        request.Method = "POST";


        string postData = "Data to post here";

        byte[] post = Encoding.UTF8.GetBytes(postData);


        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = post.Length;
        Stream reqdataStream = request.GetRequestStream();

        reqdataStream.Write(post, 0, post.Length);
        reqdataStream.Close();

        request.Credentials = CredentialCache.DefaultCredentials;

        WebResponse response = null;
        try
        {

            response = request.GetResponse();

        }
        catch (Exception ex)
        {
            Response.Write("Error Occured.");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你应该改变这些事情:

内容类型

 request.ContentType = "application/json"; 

发布数据

 string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";

URI

WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");