xml - vb.net 中的 REST 调用 : how to pass the key "file" that works in cURL

标签 xml vb.net rest post curl

我已经为这个问题苦苦挣扎了将近一个月,我阅读了我在网上能找到的所有内容,但没有解决方案。这是我的问题:我正在为 RESTful API 服务实现一个客户端,该服务必须在 vb.net 中通过 POST 调用发送 XML 文件。在获取一些 xml 格式的数据时,我能够使其正常工作,但是在发送此 Xml 文件时,我总是收到“400 错误请求错误”。

我已经想通了,这必须是必须传递给服务器的 key 问题(显然它只接受 POST 的文件上传,我不能将它作为字符串发送)。

基本上这个调用与 cURL 一起工作,但我正在努力在 vb.net 中实现我自己的调用,传递正确的值。

工作 cURL 调用:(成功传输 XML)

  c:>curl -u username:password -F "file=@filename.xml" -X POST http://hostname.com/URI?parameters

不工作的 Vb.net 代码:(这给了我 400 Bad Request)

Dim ss As String = "" 'server says...
Dim S As String = txb_username.Text & ":" & txb_password.Text
Dim EncodedString As String = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(S))
Dim req As HttpWebRequest = Nothing
Dim res As HttpWebResponse = Nothing

Try
    Dim xmlDoc As System.Xml.XmlDocument = New System.Xml.XmlDocument
    xmlDoc.XmlResolver = Nothing

    xmlDoc.Load("c:\path\file4.xml")

    Dim sXML As String = "file" & xmlDoc.InnerXml '<- This is where I try to put the "KEY"

    Dim url As String = "http:/host.com+URI"

    req = CType(WebRequest.Create(url), Net.HttpWebRequest) 'or Directcast ... 
    req.Method = "POST"
    req.Headers.Add("Authorization: Basic " & EncodedString)
    req.ContentType = "multipart/form-data"
    req.ContentLength = sXML.Length 
    req.Accept = "*/*"

    System.Windows.Forms.Application.DoEvents()

    Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(req.GetRequestStream)
    StatusUpdate(sXML)
    sw.Write(sXML)
    sw.Close()
    ss = "server says: "
    res = CType(req.GetResponse, HttpWebResponse)
     StatusUpdate(req.ToString)
    Catch ex As Exception
        StatusUpdate(ss & ex.Message)
    Finally

End Try

是因为我试图将它作为字符串发送吗? (但我还能如何将其作为文件发送?) 为此,我制作了另一个发送数据字节的程序,但这个程序也给了我“400”,因为(我假设)我没有输入"file"键。

    Dim requestStream As Stream = Nothing
    Dim fileStream As FileStream = Nothing
    Dim uploadResponse As Net.HttpWebResponse = Nothing

    Try

        Dim uploadRequest As Net.HttpWebRequest = CType(Net.HttpWebRequest.Create(URI.Text & Uri_part2.text), Net.HttpWebRequest)

        uploadRequest.Method = Net.WebRequestMethods.Http.Post
        uploadRequest.ContentType = "text/xml; charset=utf-8"
        uploadRequest.Credentials = New NetworkCredential("user", "pass")
        uploadRequest.KeepAlive = True
        uploadRequest.UserAgent = "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10"
        uploadRequest.Accept = ("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
        uploadRequest.Headers.Add("Accept-Language: en-us,en;q=0.5")
        uploadRequest.Headers.Add("Accept-Encoding: gzip,deflate")
        uploadRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")
        uploadRequest.Headers.Add("Content-Disposition: form-data; name=""file"";")
        uploadRequest.ContentType = "application/xml; charset=utf-8"

        requestStream = uploadRequest.GetRequestStream()
        fileStream = File.Open("C:\example.xml", FileMode.Open)

        Dim a As Integer

        Dim buffer(1024) As Byte
        Dim bytesRead As Integer
        While True
            a = a + 1
            bytesRead = fileStream.Read(buffer, 0, buffer.Length)
            StatusUpdate(buffer(a))

            If bytesRead = 0 Then
                Exit While
            End If
            requestStream.Write(buffer, 0, bytesRead)

        End While

       requestStream.Close()

        uploadResponse = uploadRequest.GetResponse()
        Dim responseReader As StreamReader = New StreamReader(uploadRequest.GetResponse.GetResponseStream())
        Dim x As String = responseReader.ReadToEnd()
        responseReader.Close()
        StatusUpdate(x)


    Catch ex As UriFormatException
        StatusUpdate("UriFormatException: " & ex.Message)
    Catch ex As IOException
        StatusUpdate("IOException: " & ex.Message)
    Catch ex As Net.WebException
        StatusUpdate("Net.WebException: " & ex.Message)

    Finally

        If uploadResponse IsNot Nothing Then
            uploadResponse.Close()
        End If

        If fileStream IsNot Nothing Then
            fileStream.Close()
        End If

        If requestStream IsNot Nothing Then
            requestStream.Close()
        End If

    End Try

无论如何,我还尝试了其他 2 个客户端(POSTMAN 和 REST 控制台,Google Chrome 的 2 个扩展),只有将值“file”添加到“key”字段中,我才能让它工作。我必须插入特定的 4 个字符"file"才能使其正常工作。所以,问题是:如何在 Vb.net 调用中添加相同的值?如何在工作的 Vb.net 代码中翻译 cURL 调用的代码?非常感谢您的宝贵时间和帮助!!!

在这里找到我要添加的东西的图像,wanted image

附言我不能使用 PUT,我必须使用 POST(服务器限制)

我还添加了为我的目的工作的 HTML 代码,来 self 的电脑的服务器(再次参见"file"键)

<html>
<body>
<form enctype="multipart/form-data" action="http://URI" method="POST">
<table border=0>

<tr>
<td align="right">File&nbsp;</td>
<td><input type="FILE" name="file"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>

我还从我的计算机上粘贴了一个 PERL 脚本,该脚本也适用于服务器。

  #!perl

use strict;
use LWP; # Loads all important LWP classes

my $client_id         = 1234;
my $filename          = "new_file.xml";

### Prepare to make a request

my $browser = LWP::UserAgent->new;

my $url = "http://uri.com?&xx=$client_id";

my @post_pairs = (
    #'client_id_in' => $client_id,
    'file' => [$filename],
);

my @ns_headers = (
    'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10',
    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language' => 'en-us,en;q=0.5',
    'Accept-Encoding' => 'gzip,deflate',
    'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'Authorization' => 'Basic base64EncodedCredentialsHere',
    'Content_Type' => 'form-data',
);

### Make a request
my $response = $browser->post($url, \@post_pairs, @ns_headers);
die "Can't get $url -- ", $response->status_line
        unless $response->is_success;

### Display the response
print STDOUT $response->content;

最佳答案

我认为你的问题是你真的不知道请求应该是什么样子,请使用 fiddler 查看 cURL 发送的请求并尝试使用 vb.net 实现相同的请求。在我看来,你的 secons 代码(带缓冲区,而不是 xml 序列化程序)应该可以工作......但前提是可以在服务器端理解这种结构。

关于xml - vb.net 中的 REST 调用 : how to pass the key "file" that works in cURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514779/

相关文章:

sql-server - 如何从具有动态节点数的 XML 文件创建 SQL 表?

xml - 使用 XDoc 读取 xml 文件

c# - 我想每秒显示数字时钟来刷新TextBox(Windows App)

.net - 将 bool 序列化为字符串

php - 使用 RESTful 服务保护来自跨域的 API 调用

php - 在 php 中解析 XML Caldav 请求

asp.net - asp.net 中的计时器和 UpdatePanel

vb.net - Visual Basic 中围棋游戏的洪水填充

javascript - Sharepoint 的移动应用程序

rest - 如何检索 VSTS 查询的结果