我目前正在尝试使用以下代码创建一个简单的HTTP Web请求:
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'Create initial
Dim r As HttpWebRequest = HttpWebRequest.Create(txt_Go.Text)
'Create response
Dim response As HttpWebResponse = r.GetResponse
Dim responsestream As System.IO.Stream = response.GetResponseStream
'Create a new stream reader
Dim streamreader As New System.IO.StreamReader(responsestream)
Dim data As String = streamreader.ReadToEnd
streamreader.Close()
'display data
txt_response.Text = data
Catch ex As Exception
MsgBox("Improper Input")
End Try
End Sub
End Class
如果Windows窗体包含一个文本框供用户输入API的特定URL,则API将在用户查询后返回结果。我的问题是我需要设置一个请求标头,其中包含一个密钥,我不确定如何执行此操作。
这是我要在C#中尝试实现的代码示例,我需要将其转换为可以在VB中使用的代码。
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
var uri = "https://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}&" + queryString;
var response = await client.GetAsync(uri);
}
}
}`
答案 0 :(得分:0)
在获得响应之前,您可以通过HttpWebRequest的Headers property设置请求的HTTP标头:
'Create initial
Dim r As HttpWebRequest = HttpWebRequest.Create(txt_Go.Text)
'Set the header(s) here
r.Headers("X-Bans-Header") = "Key"
r.Headers("X-Other-Header") = "Test"
'Create response
'...