How to add headers using LibCURL in julia



我想进行一个后 api 调用,并将 curl 内容类型标头设置为 application/json,

更新: 我的项目在 Linux (x86_64( 上使用 Julia 版本 0.4.7,而 Aplication 卡在curl_slist_append函数调用上。

这就是我的代码片段的样子slist = Ref{Ptr{Void}}() ; slist = curl_slist_append(slist, "Content-Type: application/json") ;

您需要创建对象LibCURL.curl_slist并将其设置为CURLOPT_HTTPHEADER选项。

但是,只要有可能,您将通过使用HTTP.jl获得更好的Julia体验:

julia> using HTTP; d = HTTP.request(:GET, "https://postman-echo.com/get?foo1=bar1",["hfoo"=>"hbar"]);
julia> println(String(d.body))
{"args":{"foo1":"bar1"},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-5ec438fa-c2bf3d5d8a300e08685f833d","content-length":"0","hfoo":"hbar","user-agent":"HTTP.jl/1.4.1"},"url":"https://postman-echo.com/get?foo1=bar1"}

如果你想实际使用LibCURL.jl这里是代码:

设置:

using LibCURL
curl = curl_easy_init()
curl_easy_setopt(curl, CURLOPT_URL, "http://postman-echo.com/get?foo1=bar1")
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1)
pars = "hfoo: hbar"
header = LibCURL.curl_slist(pointer(pars), Ptr{Nothing}())
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header)

function curl_write_cb(curlbuf::Ptr{Cvoid}, s::Csize_t, n::Csize_t, p_ctxt::Ptr{Cvoid})
sz = s * n
data = Array{UInt8}(undef, sz)
ccall(:memcpy, Ptr{Cvoid}, (Ptr{Cvoid}, Ptr{Cvoid}, UInt64), data, curlbuf, sz)
println("recd: ", String(data))
sz::Csize_t
end
c_curl_write_cb = @cfunction(curl_write_cb, Csize_t, (Ptr{Cvoid}, Csize_t, Csize_t, Ptr{Cvoid}))
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, c_curl_write_cb)

测试:

julia> res = curl_easy_perform(curl)
recd: {"args":{"foo1":"bar1"},"headers":{"x-forwarded-proto":"http","x-forwarded-port":"80","host":"postman-echo.com","x-amzn-trace-id":"Root=1-5ec441ed-4d77afc5035df618da4b4bb6","accept":"*/*","hfoo":"hbar"},"url":"http://postman-echo.com/get?foo1=bar1"}
0x00000000

最新更新