Giter Club home page Giter Club logo

curlsharp's Introduction

CurlSharp

CurlSharp is a .Net binding and object-oriented wrapper for libcurl.

libcurl is a web-client library that can provide cross-platform .Net applications with an easy way to implement such things as:

  • HTTP ( GET / HEAD / PUT / POST / multi-part / form-data )
  • FTP ( upload / download / list / 3rd-party )
  • HTTPS, FTPS, SSL, TLS ( via OpenSSL or GnuTLS )
  • Proxies, proxy tunneling, cookies, user+password authentication.
  • File transfer resume, byte ranges, multiple asynchronous transfers.
  • and much more...

CurlSharp provides simple get/set properties for libcurl's options and information functions, event-based hooks to libcurl's I/O, status, and progress callbacks, and wraps the c-style file I/O behind simple filename properties. The CurlEasy class contains has more than 100 different properties and methods to handle a wide variety of URL transfer requirements. While this may seem overwhelming at first glance, the good news is you will probably need only a tiny subset of these for most situations.

The CurlSharp library consists of these parts:

  • Pure C# P/Invoke bindings to the libcurl API.
  • Optional libcurlshim helper DLL [WIN32].
  • The CurlEasy class which provides a wrapper around a curl_easy session.
  • The CurlMulti class, which serves as a container for multiple CurlEasy objects, and provides a wrapper around a curl_multi session.
  • The CurlShare class which provides an infrastructure for serializing access to data shared by multiple CurlEasy objects, including cookie data and DNS hosts. It implements the curl_share_xxx API.
  • The CurlHttpMultiPartForm to easily construct multi-part forms.
  • The CurlSlist class which wraps a linked list of strings used in cURL.

CurlSharp is available for these platforms:

  • [Stable] Windows 32-bit
  • [Experimental] Win64 port
  • [Experimental] Mono Linux & OS X support

Examples

A simple HTTP download program...

using System;
using CurlSharp;

internal class EasyGet
{
  public static void Main(String[] args)
  {
    Curl.GlobalInit(CurlInitFlag.All);

    try
    {
      using (var easy = new CurlEasy())
      {
        easy.Url = "http://www.google.com/";
        easy.WriteFunction = OnWriteData;
        easy.Perform();
      }
    }
    finally
    {
      Curl.GlobalCleanup();
    }	
  }

  public static Int32 OnWriteData(byte[] buf, Int32 size, Int32 nmemb, object data)
  {
      Console.Write(Encoding.UTF8.GetString(buf));
      return size*nmemb;
  }
}

Simple HTTP Post example:

using (var easy = new CurlEasy())
{
    easy.Url = "http://hostname/testpost.php";
    easy.Post = true;
    var postData = "parm1=12345&parm2=Hello+world%21";
    easy.PostFields = postData;
    easy.PostFieldSize = postData.Length;
    easy.Perform();
}

HTTP/2.0 download:

using (var easy = new CurlEasy())
{
    easy.Url = "https://google.com/";
    easy.WriteFunction = OnWriteData;

    // HTTP/2 please
    easy.HttpVersion = CurlHttpVersion.Http2_0;

    // skip SSL verification during debugging
    easy.SslVerifyPeer = false;
    easy.SslVerifyhost = false;

    easy.Perform();
}

More samples are included in the Samples folder.

Credits

CurlSharp Written by Dr. Masroor Ehsan.

CurlSharp is based on original code by Jeff Phillips libcurl.NET. Original code has been modified and greatly enhanced.


CurlSharp Copyright © 2013-17 Dr. Masroor Ehsan

curlsharp's People

Contributors

cyberscooby avatar dominikhura avatar lailongwei avatar masroore avatar pjf avatar silasary avatar stil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

curlsharp's Issues

CurlEasy causes a large memory leak.

Hello again, faced a problem on Linux Mono 3.0 CurlEasy causes a large memory leak.
My test code:

public static void DoTestCurlEasy()
{
bool wykonuj = true;
int nrpetli = 0;

while (wykonuj)
{
    using (var easy = new CurlEasy())
    {
        easy.Url = "http://www.xxxxxxx.com/dotest.html";
        easy.WriteData = null;
        easy.WriteFunction = OnWriteData;
        easy.Perform();
    }

    Console.WriteLine("nrpetli: {0}", nrpetli);
    nrpetli++;
    Thread.Sleep(200);
}

}

public static Int32 OnWriteData(Byte[] buf, Int32 size, Int32 nmemb, Object extraData)
{
//var userData = (string)extraData;
//Console.Write(Encoding.UTF8.GetString(buf));
return size * nmemb;
}
Linux htop
Running is 0.9 MEM%

  • 10 minutes
    1.1 MEM%
    1.2 MEM%
    ...
    2.0 MEM%
    And all the time the leak is getting bigger and RAM occupancy increases :(
    Please check at the time, it may also fail to fix this :)
    Thank you

CurlEasy.SetOpt() string parameter bug

Even setting the parameters works and does not work. I think it should work interchangeably so and so.

//easy.UserAgent = "Do UserAgent"; // Works
easy.SetOpt(CurlOption.UserAgent, "Do UserAgent SetOpt"); // Does not work

//easy.Proxy = "xxx.xxx.xxx.xxx:21320"; // Works
easy.SetOpt(CurlOption.Proxy, "xxx.xxx.xxx.xxx:21320"); // Does not work

//easy.PostFields = postData; // Works :)
easy.SetOpt(CurlOption.PostFields, postData); // Does not work

//easy.Encoding = "gzip, deflate"; // Works
easy.SetOpt(CurlOption.Encoding, "gzip, deflate"); // Does not work

easy.FollowLocation = true; // Works or
easy.SetOpt(CurlOption.FollowLocation, true); // Works

At the time, please check yourself

I Know is already asked, but, cant compile demos. System.DllNotFoundException

I read another Issues and try the solutions...

Before all... Am using Windows 10 x64 operating System.

I am trying to run WinSamples, I already target to x86 and Debug my solution. When I start the project the Form appears and when I click on "Get Source" Button I receive the next error:

System.DllNotFoundException: 'Can't load the file DLL 'libcurl': Can't find specified module. (Exception of HRESULT: 0x8007007E)'

So copy the DLL from the folder libs/i386/libcurl.dll and paste inside WinSamples/bin/Debug and start the program again. But I get the same error.

I try including the dll on the project.... copy all the others dll files from i386

What else can I do? What I am doing wrong? Thanks in advance

help in MultiDemo

i am use your CurlSharp's sample
all is ok but "MultiDemo" always wrong ,
line 49 : var rc = multi.Select(1000); // one second alway return -1
waiting for your help!

TLS error handling broken

Hello,

currently it seems like TLS errors aren't handled in any way.
If I connect to a host with invalid certificate Perform() returns OK error code but the resulting document is empty.

CurlEasy.ErrorBuffer is also always empty.
It seems like it's never initialized and the set method looks like it's not correctly used.
https://curl.haxx.se/libcurl/c/CURLOPT_ERRORBUFFER.html

Trying samples - missing libcurl64.dll

Projects compiled ok. When running, for example, upload.exe, get the following message:

System.DllNotFoundException: Unable to load DLL 'libcurl64.dll': The specified module could not be found.

Need to be able to upload a file from a local machine to a location on a server, so ftp upload seems to be the obvious. Need to do it in C#, as part of a larger program.

Thanks very much for any help.

Problem loading libcurl.dll

Hello,

I thought I would make my happiness with CurlSharp, but I have struggled for 3 days.
Unable to launch the project. An error appears when loading the LibCurl.dll dll on the _initCode = NativeMethods.curl_global_init ((int) flags) instruction;
For information, I am using Windows 10 version 1809 64 bits and I am loading the solution with Visual Studio 2019
At first, I have an error: libcurl not found
After copying libcurl.dll to the System32 directory I have a System.BadImageFormatException exception

I also copied the DLLs from CurlSharp \ libs \ i386 to CurlSharp \ Samples \ bin as shown in issues # 36 but it's not better.

Has anyone ever had this problem and found a solution?

Support for TLS 1.2

Hi, I was trying to use your library for TLS 1.2 https (ssl) requests. However, I could not find CURL_SSLVERSION_TLSv1_2 defined in in the calling c# wrapper. Could you pl give some inputs or pointers in this regard to make it work for TLS 1.2 Thanks.

THANK YOU!

Github doesn't provide a good way that I know of to say thank you, but holy smokes, THANK YOU. Curlsharp is amazing, doubly so due to the wonderful examples directory. You totally rock. <3

The POST method not working CurlSharp

The POST method not working CurlSharp. The same does not operate
easy.PostFields> FileUpload.cs not working
easy.HttpPost> BookPost.cs not working
64 Bit

lib file name error on ubuntu

the default file name can not load curl lib on ubuntu 16.04
private const string LIBCURL = "libcurl";
this works
private const string LIBCURL = "libcurl.so.3";

easy auth

Hi,
I want to wrap my native curl call

curl.exe -i -Uuser:token -O "http://path/to/file.zip"

using CurlSharp.

First question:
Do I have to set user and token by

easy.UserAgent = "user";
easy.UserPwd = "token";

in CurlSharp?

Second question:
Can you give an example on how to modify OnWriteData to handle my zip file.

Thanks a lot!

Response code confusion

Hi,

I have been using the CurlSharp Library for some time now and Ive noticed I get a response code of 200 on a successful HttpGet. I am a bit confused as to what this means exactly other than(from what I can Guess) is the HTTPGET was successful.

I have looked at the enums but haven't found any 200.

do you mind explaining it?

Update to libcurl 7.52

This is a pretty awesome wrapper, would be great to see it support libcurl 7.52 and a the curlmopt_XXX for enabling full HTTP/2

UnsupportedProtocol

Hi!

I'm getting UnsupportedProtocol when trying to make a request that uses CurlSharp like this:

                CurlSharp.Curl.GlobalInit(CurlInitFlag.All);
                using (var easy = new CurlEasy())
                {
                    easy.WriteFunction = OnWriteData;
                    easy.PostFields = postData;
                    var header = new CurlSlist();
                    header.Append("ContentType: application/x-www-form-urlencoded");
                    easy.SetOpt(CurlOption.HttpHeader, header);
                    easy.PostFieldSize = postData.Length;
                    easy.UserAgent = "Test-Agent";
                    easy.FollowLocation = true;
                    easy.Url = authurl;
                    easy.Post = true;
                    curlcode = easy.Perform();
                    responseCode = easy.ResponseCode;
                }
               CurlSharp.Curl.GlobalCleanup();

the authurl is a https SSL/TLS url...

What is wrong?

Thanks

Curl SSL Two way communiation

any one can help me out with curl ssl 2 way communication.
using the below code snippet

using (var easy = new CurlEasy())
{
easy.AutoReferer = true;
easy.FollowLocation = true;
easy.Url = textBoxUrl.Text.Trim();
easy.CaInfo = @"------------.crt-----------------------------";
easy.CaPath = @"----------------
.crt-------------------------";
easy.SslKey = @"-----------.key------------------------------";
easy.SslCert = @"----------------
.crt-------------------------";

            easy.WriteFunction = OnWriteData;
            easy.Perform();
        }

provide me any example c# code for curl ssl 2 way communication

getting below error

"Unknown CA (48)"

Thanks.

Using curlsharp for veracode

First of all my apologies; This is not an issue.

I am trying to execute veracode api using curlSharp library. Manually I can execute the command as below.
curl --compressed -u [veracodeuser]:[mypassword] https://analysiscenter.veracode.com/api/4.0/getapplist.do -F 'include_user_info=true'

using (var easy = new CurlEasy())
{
easy.UserPwd = "Password"
easy.AutoReferer = true;
easy.FollowLocation = true;
easy.Url = textBoxUrl.Text.Trim();
easy.WriteFunction = OnWriteData;
easy.Perform();
}

I couldn't figure out how to pass username and --compressed -F options. Could you please let me know if I can accomplish this with CurlSharp.

I appreciate your response.

CurlHttpMultiPartForm > CurlFormOption.File does not work :(

Hello again. It does not work to send a file or send wrong? My test C# code:
string avatar = Application.StartupPath + @"\avatary\myface.jpg";
var mf = new CurlHttpMultiPartForm();
mf.AddSection(CurlFormOption.CopyName, "parm1", CurlFormOption.CopyContents, "value1", CurlFormOption.End);
mf.AddSection(CurlFormOption.CopyName, "parm2", CurlFormOption.CopyContents, "value2", CurlFormOption.End);
if (File.Exists(avatar))
{
mf.AddSection(CurlFormOption.CopyName, "uploadedfile", CurlFormOption.File, avatar, CurlFormOption.ContentType, "application/application/binary", CurlFormOption.End);
Console.WriteLine(avatar);
}
easy.HttpPost = mf;

$value) { echo "$header: $value \r\n"; } ?>

My OUT:
Array
(
[parm1] => value1
[parm2] => value2
)
Array
(
)
Host: www.testsite.com
Connection: close
Content-Length: 246
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0
Accept-Encoding: gzip,deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Cache-Control: max-age=0
Pragma: no-cache
Content-Type: multipart/form-data; boundary=------------------------e489e380b38b4322

NativeMethods problem

Please ignore the Chinese message.

I'v tried 0.5.0 and 0.5.1 with Visual Studio 2017. And it works great.
But with the 2017/08/10 build... Error occurred at NativeMethods.

System.TypeInitializationException: 'CurlSharp.NativeMethods' 的類型初始設定式發生例外狀況。 ---> System.DllNotFoundException: 無法載入 DLL 'api-ms-win-core-sysinfo-l1-2-0.dll': 找不到指定的模組。 (發生例外狀況於 HRESULT: 0x8007007E)
於 Interop.mincore.GetNativeSystemInfo(SYSTEM_INFO& lpSystemInfo)
於 System.Runtime.InteropServices.RuntimeInformation.get_OSArchitecture()
於 CurlSharp.NativeMethods..cctor()
--- 內部例外狀況堆疊追蹤的結尾 ---

CurlEasy.setWriteData() bug

when I second times call this method, old saved _curlWriteData not call freeHandle() to free, It trigger GC memory leak

How do I upload wav file to server?

when i use upload sample,i get error:
Object 包含非基元或非直接复制到本机结构中的数据。
Object contains non-primitive or non-blittable data. (Parameter 'value')
after i add : easy.SetOpt(CurlOption.HttpHeader, "content - type = audio / x - raw");
error occur again
thanks

Suggest Set NoSignal = true When create CurlEasy object

libcurl in multi-thread will coredump if enabled signal support(libcurl internal use signal to implemented dns query timeout timer), will coredump, because signal mechanism in multi-thread Situation behavior is undefined!
this will lost dns query timeout function, but we can suggest user compiled c-ares support libcurl to restore dns query timeout function.
Just a suggesstion :-)

WinSamples can not work

CurlSharp\Samples\WinSamples\WinSamples.csproj
this project missing libcurl.dll

When I copy the libcurl.dll from CurlSharp\libs\i386
still can not load the dll

Basic Auth

Is there a way to do basic authentication with this library ? If so, then how?

curl upload not working when upload this

When i post a curl url i was facing this strange issue

message
{"Object contains non-primitive or non-blittable data."}
at System.Runtime.InteropServices.GCHandle.InternalAlloc(Object value, GCHandleType type)
at System.Runtime.InteropServices.GCHandle.Alloc(Object value, GCHandleType type)
at CurlSharp.CurlEasy.getHandle(Object obj) in d:\sharedfiles\Jagan\CurlSharp-master\CurlSharp-master\CurlSharp\CurlEasy.cs:line 1526
at CurlSharp.CurlEasy.setReadData(Object data) in d:\sharedfiles\Jagan\CurlSharp-master\CurlSharp-master\CurlSharp\CurlEasy.cs:line 252
at CurlSharp.CurlEasy.set_ReadData(Object value) in d:\sharedfiles\Jagan\CurlSharp-master\CurlSharp-master\CurlSharp\CurlEasy.cs:line 330
at Upload.Upload.Main(String[] args) in d:\sharedfiles\Jagan\CurlSharp-master\CurlSharp-master\Samples\Upload\Upload.cs:line 36

Curl command is

curl -i -X POST -H "Content-Type: multipart/form-data" -H "Authorization: SIMPLE Y2F0Y2h0aGVtb21lbjpjYXRjaHRoZW1vbWVudDExMQ==" -F "card={"text":"sometext", "userName":"%USERNAME%", "screenName":"screenName", "avatarUrl":"https://www.google.com/images/srpr/logo11w.png\"};type=application/json" -F "pic=@c:\users\my\desktop\download.jpg" "https://socialwall.cvent.com/livestream/api/event/395b4759-8b93-4fb1-b33b-387c3928c1ca/socialpost" -v

below code is my implementation of above curl command

public static void Main(String[] args)
{
try
{

            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download.jpg");
            Curl.GlobalInit(CurlInitFlag.All);

            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                string _cred = string.Format("{0} {1}", "SIMPLE", "Y2F0Y2h0aGVtb21lbjpjYXRjaHRoZW1vbWVudDExMQ==");
                string url = "https://socialwall.cvent.com/livestream/api/event/395b4759-8b93-4fb1-b33b-387c3928c1ca/socialpost";
                var card = new Card
        {
            text = "Ohmygod",
            userName = "CatchTheMoment",
            screenName = "Socialpost",
            avatarUrl = "https://www.google.com/images/srpr/logo11w.png"
        };
        var jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(card);
                using (var easy = new CurlEasy())
                {
                    easy.ReadFunction = OnReadData;
                    easy.ReadData = fs;
                    var headers = new CurlSlist();
                    headers.Append("Content-Type: multipart/form-data");
                    headers.Append("Accept: */*");
                    headers.Append("user-agent:Mozilla/4.0");
                    headers.Append("Authorization0:"+_cred);
                    headers.Append("Except: 100-continue");

                    easy.HttpHeader = headers;
                    easy.DebugFunction = OnDebug;
                    easy.SetOpt(CurlOption.Verbose, true);
                    easy.SetOpt(CurlOption.Header, true);
                    easy.ProgressFunction = OnProgress;
                    easy.Url = url;
                    easy.Upload = true;
                    easy.InfileSize = fs.Length;
                    easy.PostFields = "card="+jsonstring;
                    easy.PostFieldSize = jsonstring.Length;
                    easy.Perform();
                    Console.ReadLine();
                }
            }

            Curl.GlobalCleanup();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    public static Int32 OnReadData(Byte[] buf, Int32 size, Int32 nmemb, Object extraData)
    {
        var fs = (FileStream) extraData;
        return fs.Read(buf, 0, size*nmemb);
    }

    public static void OnDebug(CurlInfoType infoType, String msg, Object extraData)
    {
        Console.WriteLine(msg);
    }

    public static Int32 OnProgress(Object extraData, Double dlTotal,
        Double dlNow, Double ulTotal, Double ulNow)
    {
        Console.WriteLine("Progress: {0} {1} {2} {3}",
            dlTotal, dlNow, ulTotal, ulNow);
        return 0; // standard return from PROGRESSFUNCTION
    }
    public class Card
    {

        public string text { get; set; }
        public string userName { get; set; }
        public string screenName { get; set; }
        public string avatarUrl { get; set; }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.