如何在julia中使用LibCURL添加标题

如何在julia中使用LibCURL添加标题,julia,libcurl,Julia,Libcurl,我想进行一个post-api调用,并将curl-content-type头设置为application/json 更新: 我的项目在Linux(x86_64)上使用Julia版本0.4.7,应用程序在curl_slist_append函数调用时陷入困境 这就是我的代码片段的外观slist=Ref{Ptr{Void}}();slist=curl\u slist\u append(slist,“内容类型:application/json”)您需要创建对象LibCURL.curl\u slist并将其

我想进行一个post-api调用,并将curl-content-type头设置为application/json

更新: 我的项目在Linux(x86_64)上使用Julia版本0.4.7,应用程序在curl_slist_append函数调用时陷入困境


这就是我的代码片段的外观
slist=Ref{Ptr{Void}}();slist=curl\u slist\u append(slist,“内容类型:application/json”)

您需要创建对象
LibCURL.curl\u slist
并将其设置为
CURLOPT\u 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

感谢@Przemyslaw Szufel,这对Julia1.x非常有效,我的项目基于Julia版本0.4.7 Linux(x86_64),应用程序在curl_slist_append函数callDear@Nikhil Navin-0.4.7是一个非常旧的版本,我想大多数库都不会再使用它了。我能给你的建议就是尝试升级(如果可能的话)。