将使用WinHttp.WinHttpRequest的短vb6代码迁移到c#或vb.net

时间:2016-07-22 17:50:09

标签: c# vb.net vb6 httpwebrequest

有人可以指导我如何将该vb6代码转换为c#或visual basic.net。我试图使用System.Net.WebRequest()类,但没有成功(我treys的所有内容都引发了另一个例外,因此我认为添加我的c#代码将没有用处。)

此代码工作正常(我使用vba编辑器对其进行了测试)。

澄清:我不想让我的工作做起来我只需要理解GetHTTPResponse()函数中前11行的等效方法到System.Net.WebRequest()类medhods,这就足够了从那时起,我将能够独自处理它。

非常感谢您的时间和考虑。

Function ReadToken(s)
    Dim X()
    ReDim X(0)
    s = Replace(s, Chr(34), "")
    bRes = False
    Set RegExp = CreateObject("VBScript.RegExp")
    RegExp.IgnoreCase = True
    RegExp.Pattern = "token\:(.+?),type\:(.+?),expires_in\:(.+?)"

    bRes = RegExp.test(s)
    If bRes Then
        Set oMatches = RegExp.Execute(s)
        ReDim X(2)
        X(0) = oMatches(0).subMatches(0)
        X(1) = oMatches(0).subMatches(1)
        X(2) = oMatches(0).subMatches(2)
    End If
    ReadToken = X

End Function

Function GetHTTPResponse(ByVal Id As Long) As String
' On Error Resume Next
    Const username = "username"
    Const password = "password"
    sURL = "https://api.exoclick.com/v1/login"
    Set oXMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    With oXMLHTTP
        .Open "Post", sURL, False
        .setRequestHeader "Content-Type", "application/json"
        params = "{""username"":" & Chr(34) & username & Chr(34) & ", ""password"":" & _
                Chr(34) & password & Chr(34) & "}"
        .send params
        If .Status = 200 Then
            Response = .ResponseText
            Token = ReadToken(Response)
            Authorization = "{""type"":" & Chr(34) & Token(1) & _
                            Chr(34) & ",""token"":" & Chr(34) & Token(0) & Chr(34) & "}"
            .abort
            sURL = "https://api.exoclick.com/v1/statistics/advertiser/date"
            params = "{""campaignid"":" & Id & "}"
            .Open "GET", sURL, False
            .setRequestHeader "Content-Type", "application/json"
            .setRequestHeader "Authorization", Authorization
            .send params
            GetHTTPResponse = .ResponseText
        End If
    End With
    Set oXMLHTTP = Nothing
End Function

1 个答案:

答案 0 :(得分:3)

在C#中执行Web请求的最佳方法是使用HttpClient,只要您支持.NET 4.5+即可。这是一个简单的例子:

using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
       { "username", username },
       { "password", password }
    };

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var content = new FormUrlEncodedContent(values);
    var response = await client.PostAsync(sURL, content);
    if (response.IsSuccessStatusCode)
    {    
        var response = await response.Content.ReadAsString();
        // then repeat for the next request
    }
}

Here是学习HttpClient的好资源。

请务必使用async关键字标记GetHTTPResponse方法。