0

我从 async_sinatra 0.5.0 升级到 1.0 因为后者解决了这个问题

到现在为止还挺好。但是当我回到包含身份验证的原始应用程序(而不是我的测试应用程序)时,它停止了工作。我正在使用 vb.net 进行网络请求,这在 0.5.0 下运行良好,但现在失败了

"The remote server returned an error: (401) Unauthorized."

这是我的红宝石代码:

#gem  'async_sinatra', '0.5.0'
require 'sinatra/async'

class AsyncQueryServer < Sinatra::Base
  register Sinatra::Async

  set :server, 'thin'
  set :port, 19876
  enable :show_exceptions

  helpers do
    def protected!
      unless authorized?
        response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
        throw(:halt, [401, "Not authorized\n"])
      end
    end

    def authorized?
      @auth ||=  Rack::Auth::Basic::Request.new(request.env)
      begin
        puts "@auth.provided? #{@auth.provided?}"
        puts "@auth.basic? #{@auth.basic?}"
        puts "@auth.credentials #{@auth.credentials}"
      rescue Exception => e
        puts e.message
      end
      @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['myusername', 'mypassword']
    end
  end

  apost '/execfqy' do
    protected!
    body request.body.string
  end

  not_found do
    puts "in not found, request.fullpath #{request.fullpath}"
    puts "in not found, request.request_method #{request.request_method}"
    puts "in not found, request.params #{request.params}"
    puts "in not found, request.class #{request.class}"

    redirect '/'
  end

end

AsyncQueryServer.run!

我确信这是升级到 async_sinatra 1.0,因为如果我取消注释

#gem  'async_sinatra', '0.5.0'

它按预期工作。

有趣的是,puts 语句的输出是授权的?两个版本都相同,并显示:

@auth.provided? false 
undefined method `split' for nil:NilClass
@auth.provided? true 
@auth.basic? true 
@auth.credentials ["myusername", "mypassword"]

这里是来自 vb.net 的片段,基于这个页面,它产生了 webrequest:

Private Function GetOutput(jsonDataBytes As Byte()) As String
        Dim req As WebRequest
        Dim res As String
        '        Dim cred As New Net.NetworkCredential("myusername", "mypassword")
        Dim cred As New Net.NetworkCredential("myusername", "mypassword")
        Dim req_str As String

        req_str = _urlString & ":" & _portString & "/execfqy"

        req = WebRequest.Create(req_str)

        req.ContentType = "application/json"
        req.Method = "POST"
        req.ContentLength = jsonDataBytes.Length
        req.Credentials = cred

        Dim stream = req.GetRequestStream()
        stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
        stream.Close()

        Try
            Dim response = req.GetResponse().GetResponseStream()
            Dim reader As New StreamReader(response)
            res = reader.ReadToEnd()
            reader.Close()
            response.Close()
        Catch e As WebException
            Throw New NoResultsError("Request return nil results with error: " & e.Message)
            res = Nothing
        End Try

        Return res
End Function 

任何帮助/建议/重定向将不胜感激。

TIA

4

1 回答 1

0

以下是我修复它的方法:我放弃了 vb.net 原生方法,并使用了 chilkat 的http 组件。效果很好。这是代码:

Private Function GetOutputChilkatPostJson(jsonData As String) As String
    'Dim req As New Chilkat.HttpRequest()
    Dim http As New Chilkat.Http()
    Dim res As String
    Dim req_str As String
    Dim success As Boolean

    req_str = _urlString & ":" & _portString & "/execfqy"

    '  Any string unlocks the component for the 1st 30 days.
    success = http.UnlockComponent("Anything for 30-day trial")
    If (success <> True) Then
        MsgBox(http.LastErrorText)
        Exit Function
    End If


    '  This example duplicates the HTTP POST shown at
    '  http://json.org/JSONRequest.html

    '  Specifically, the request to be sent looks like this:
    '  
    'POST /request HTTP/1.1
    'Accept: application/jsonrequest
    '        Content(-Encoding) : identity()
    'Content-Length: 72
    'Content-Type: application/jsonrequest
    'Host:   json.penzance.org()

    '{"user":"doctoravatar@penzance.com","forecast":7,"t":"vlIj","zip":94089}


    '  First, remove default header fields that would be automatically
    '  sent.  (These headers are harmless, and shouldn't need to
    '  be suppressed, but just in case...)
    http.AcceptCharset = ""
    http.UserAgent = ""
    http.AcceptLanguage = ""
    http.Login = "myusername"
    http.Password = "mypassword"
    '  Suppress the Accept-Encoding header by disallowing
    '  a gzip response:
    http.AllowGzip = False

    '  If a Cookie needs to be added, it may be added by calling
    '  AddQuickHeader:
    'http.AddQuickHeader("Cookie", "JSESSIONID=1234")

    '  To use SSL/TLS, simply use "https://" in the URL.

    '  IMPORTANT: Make sure to change the URL, JSON text,
    '  and other data items to your own values.  The URL used
    '  in this example will not actually work.

    Dim resp As Chilkat.HttpResponse
    Try
        resp = http.PostJson(req_str, jsonData)
        res = resp.BodyStr
    Catch e As WebException
        Throw New NoResultsError("Request return nil results with error: " & e.Message)
        res = Nothing
    End Try
    Return res
End Function
于 2012-05-03T16:14:51.610 回答