Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

curl Request with ASP.NET

I have read some other posts on Stack but I can't get this to work. It works fine on my when I run the curl command in git on my windows machine but when I convert it to asp.net it's not working:

 private void BeeBoleRequest()
    {   
        string url = "https://mycompany.beebole-apps.com/api";

        WebRequest myReq = WebRequest.Create(url);            

        string username = "e26f3a722f46996d77dd78c5dbe82f15298a6385";
        string password = "x";
        string usernamePassword = username + ":" + password;
        CredentialCache mycache = new CredentialCache();
        mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
        myReq.Credentials = mycache;
        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        WebResponse wr = myReq.GetResponse();
        Stream receiveStream = wr.GetResponseStream();
        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string content = reader.ReadToEnd();
        Response.Write(content);
    }

This is the BeeBole API. Its pretty straight fwd. http://beebole.com/api but I am getting a following 500 error when I run the above:

The remote server returned an error: (500) Internal Server Error.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default HTTP method for WebRequest is GET. Try setting it to POST, as that's what the API is expecting

myReq.Method = "POST";

I assume you are posting something. As a test, I'm going to post the same data from their curl example.

string url = "https://YOUR_COMPANY_HERE.beebole-apps.com/api";
string data = "{"service":"absence.list", "company_id":3}";

WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentLength = data.Length;
myReq.ContentType = "application/json; charset=UTF-8";

string usernamePassword = "YOUR API TOKEN HERE" + ":" + "x";

UTF8Encoding enc = new UTF8Encoding();

myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(usernamePassword)));


using (Stream ds = myReq.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length); 
}


WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...