我有以下CURL命令,我想将其转换为c#webapi调用。
curl -H "Content-Type: application/x-www-form-urlencoded" \
-H "client_id: YOUR-CLIENT-ID" \
-H "client_secret: YOUR-CLIENT-SECRET" \
-d "mailbox_id=YOUR-MAILBOX-ID" \
--data-urlencode email@/path/to/email/contents.eml \
"https://api.abc.com/v2/add"
我需要帮助的部分是如何将邮箱ID和数据添加为url编码。它也从磁盘中获取电子邮件。我可以添加字节数组吗?
这是我的c#代码示例。 我只需要在那里添加mailid和电子邮件内容。
public static string WebRequestWithByte(byte[] postData)
{
var url = @"https://api.abv.com/v2/add";
var clientId = "wewew";
var clientSecret = "df58ffed4bc0bc41";
string ret = string.Empty;
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Headers.Add("client_id", clientId);
webRequest.Headers.Add("client_secret", clientSecret);
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(payloadStr);
}
}
答案 0 :(得分:0)
您可以使用以下代码。我想你想要Post
电话。您可以将数据添加到Dictionary
,然后将其转换为字节数组。
-d
和--data
相同。
此代码仅供您参考,您可以相应地修改它。
private static String Post(String url,
int timeout)
{
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
if (timeout != 0)
req.Timeout = timeout;
req.Headers.Set("client_id", "client_id");
req.Headers.Set("client_secret", "client_secret");
Dictionary<String, String> data = new Dictionary<String, String>();
data.Add("mailbox_id", "mailbox_id");
byte[] rawData = Encoding.UTF8.GetBytes(Encode(data));
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = rawData.Length;
String ret = null;
using (Stream s = req.GetRequestStream())
{
s.Write(rawData, 0, rawData.Length);
using (HttpWebResponse res = req.GetResponse() as HttpWebResponse)
{
using (Stream s2 = res.GetResponseStream())
{
using (StreamReader r = new StreamReader(s2, Encoding.UTF8))
{
ret = r.ReadToEnd();
}
}
}
}
return ret;
}
public static String Encode(Dictionary<String, String> data)
{
StringBuilder s = new StringBuilder();
foreach (KeyValuePair<String, String> o in data)
{
s.AppendFormat("{0}={1}&", o.Key, HttpUtility.UrlEncode(o.Value));
}
char[] trim = { '&' };
String ret = s.ToString().TrimEnd(trim);
return ret;
}