You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RestSharp Get请求无法发送请求体问题求助(.NET Framework 4.8)

解决GET请求带请求体的API调用问题

问题分析

你遇到的情况是API强制要求用GET方法但需要传递JSON请求体,RestSharp出于HTTP规范的默认限制阻止了GET请求携带RequestBody,同时POST方法又被API拒绝,得绕开RestSharp的限制来实现调用。

解决方案:使用HttpWebRequest实现

直接用.NET Framework自带的HttpWebRequest可以强制发送带请求体的GET请求,不受RestSharp的限制,代码如下:

Dim url As String = "https://smartlane.com.pk/api/production/consignment/track"
Dim jsonBody As String = "{" & vbLf & "    ""store_order_id"":[" & vbLf & "        ""1001"",""1002""" & vbLf & "    ]" & vbLf & "}"

' 创建请求对象
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
request.Method = "GET"
request.ContentType = "application/json"
request.Headers.Add("Authorization", "kA0HzgWQRaYRepL8ol8jmkHVJJIZRDQfx1zEqB")

' 写入请求体
Using streamWriter As New StreamWriter(request.GetRequestStream())
    streamWriter.Write(jsonBody)
End Using

' 获取响应
Try
    Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
        Using streamReader As New StreamReader(response.GetResponseStream())
            Dim responseContent As String = streamReader.ReadToEnd()
            Console.WriteLine(responseContent)
        End Using
    End Using
Catch ex As WebException
    ' 处理异常,读取错误响应内容
    Using errorResponse As HttpWebResponse = DirectCast(ex.Response, HttpWebResponse)
        Using streamReader As New StreamReader(errorResponse.GetResponseStream())
            Dim errorContent As String = streamReader.ReadToEnd()
            Console.WriteLine("请求错误:" & errorContent)
        End Using
    End Using
End Try

补充说明

  1. HTTP规范中GET方法不推荐携带请求体,但部分API厂商会出于特殊需求这么设计,原生的HttpWebRequest不会做额外限制,能满足这类场景。
  2. 如果坚持要用RestSharp,需确保使用RestSharp 107及以上版本,并通过配置启用GET带请求体的支持:
Dim client = New RestClient("https://smartlane.com.pk/api/production/consignment/track")
client.Options.AllowGetMethodBody = True ' 开启GET带body的支持

Dim request = New RestRequest()
request.Method = Method.Get
request.AddHeader("Authorization", "kA0HzgWQRaYRepL8ol8jmkHVJJIZRDQfx1zEqB")
request.AddHeader("Content-Type", "application/json")
Dim body = "{" & vbLf & "    ""store_order_id"":[" & vbLf & "        ""1001"",""1002""" & vbLf & "    ]" & vbLf & "}"
request.AddStringBody(body, ContentType.Json)

Dim response = client.Execute(request)
Console.WriteLine(response.Content)

注意:旧版本RestSharp没有AllowGetMethodBody配置项,此时原生HttpWebRequest是更稳妥的选择。

内容的提问来源于stack exchange,提问作者Samee Ullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:52:40