[英]How to send a GET request with body to an API Rest C#?
嗨,我正在做一個Windows窗體項目以與API交互。 到目前為止,我已經能夠開發該應用程序,但是現在我遇到了一個無法解決的問題。 我正在嘗試像這樣的GET請求中發送json正文:
范例:
注意:該示例顯示了如何獲取溫度傳感器最近三天的平均值。 請求
GET http://api.effilogics.com/nodes/583/parameters/30/data?resolution=day&groupby=avg
{begin: '2014-04-21T16:13:30+02:00', end: '2014-04-24T15:44:12+02:00'}
我不確定是否要正確發送正文(日期開始和結束),因為我收到一條消息錯誤,指出無法使用這種冗長的類型發送文本內容。 我的問題是如何在GET請求中發送數據/時間主體? 我無法更改為POST請求。
代碼的一部分是這樣的:
public void Request4(String url)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Method = "GET";
myReq.ContentType = "application/json";
myReq.KeepAlive = true;
myReq.Headers.Set("Cache-Control", "no-store");
myReq.Headers.Set("Pragma", "no-cache");
myReq.Headers.Set("Authorization", token_type + " " + access_token);
datestruct dateST = new datestruct();
dateST.begin = string.Concat("'begin':",DateTime.UtcNow.ToString("s",System.Globalization.CultureInfo.InvariantCulture),"+02:00");
byte[] getBytes = Encoding.UTF8.GetBytes(dateST.begin);
myReq.ContentLength = getBytes.Length;
Stream body = myReq.GetRequestStream();
body.Write(getBytes, 0, getBytes.Length);
body.Close();
//Obtenim la resposta del servidor
WebResponse myResponse = myReq.GetResponse();
Stream rebut = myResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(rebut, Encoding.UTF8);
//richTextBox6.AppendText(readStream.ReadToEnd() + "\n");
string info = readStream.ReadToEnd();
split3 = info.Split(new char[] { '[', '{', ',', '}', ']' });
int mida = split3.Length;
Array.Resize(ref split3, mida - 2);
Array.Reverse(split3);
mida = split3.Length;
Array.Resize(ref split3, mida - 3);
Array.Reverse(split3);
foreach (string s in split3)
{
richTextBox6.AppendText(s);
richTextBox4.AppendText(s);
}
myResponse.Close();
readStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
如果有人可以幫助我,我將非常感激。 謝謝
正如我在對您的問題的評論中所解釋的那樣,通常GET請求沒有主體,因此我懷疑API會接受它(因此會出現錯誤消息),請嘗試將其編碼到url中(只要確保您的json對象結構與API接受的參數)
嘗試使用Uri.EscapeUriString之類的方法構建您的網址:
http://api.effilogics.com/nodes/583/parameters/30/data?resolution=day&groupby=avg + Uri.EscapeUriString(JSon)
PS SOAP UI(可能有點硬核)或Fiddler 2(易於使用)是使用REST時非常好的工具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.