HttpResponse response;
request.AllowAutoRedirect = false;
request.UserAgent = HttpHelper.IEUserAgent();
response = request.Post("https://www.site.com", "value=1");
But after request, program trys to open file value=1. Why?
Try this option, code:
using (var request = new HttpRequest())
{
request.UserAgent = HttpHelper.RandomUserAgent();
request.Proxy = Socks5ProxyClient.Parse("127.0.0.1:1080");
var reqParams = new StringDictionary();
reqParams["login"] = "neo";
reqParams["password"] = "knockknock";
string content = request.Post(
"www.whitehouse.gov", reqParams).ToText();
string secretsGovernment = content.Substring("secrets_government=\"", "\"");
}
And read documentation here
Post(string address, string path) - send file. You can set the parameters as:
1:
using (var request = new HttpRequest())
{
var reqParams = new RequestParams();
reqParams["login"] = "neo";
reqParams["password"] = "knockknock";
string content = request.Post(
"www.whitehouse.gov", reqParams).ToString();
}
2:
using (var request = new HttpRequest("www.whitehouse.gov"))
{
request
.AddParam("login", "neo")
.AddParam("password", "knockknock");
string content = request.Post("/").ToString();
}
3:
using (var request = new HttpRequest())
{
var reqParams = new Dictionary<string, string>()
{
{"login", "neo"},
{"password", "knockknock"},
};
var httpContent = new FormUrlEncodedContent(reqParams);
string content = request.Post(
"www.whitehouse.gov", httpContent).ToString();
}
4:
using (var request = new HttpRequest())
{
string reqStr = "param1=value1¶m2=value2";
string content = request.Post(
"www.whitehouse.gov", reqStr,
"application/x-www-form-urlencoded").ToString();
}
Related
I am trying to build a console app that reads the data from SharePoint list.
But i dont want to pass the user credentials in order to authenticate, instead use the token. Is this possible?
I tried using the following code but i get forbidden error while trying to GetFormDigest
static void Main(string[] args)
{
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/web/lists/getbytitle('sd')/GetItems");
string sResult = string.Empty;
string stringData = "{'query' : {'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml':'<View><Query><Where><Eq><FieldRef Name =\"Title\"/><Value Type=\"Text\">HR</Value></Eq></Where></Query></View>'}}";
HttpWebRequest oWebRequest = (HttpWebRequest)WebRequest.Create(oUri);
oWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentType = "application/json;odata=verbose";
oWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());
oWebRequest.ContentLength = stringData.Length;
StreamWriter writer = new StreamWriter(oWebRequest.GetRequestStream());
writer.Write(stringData);
writer.Flush();
WebResponse wresp = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
}
public static string GetFormDigest()
{
string sFormDigest = null;
string sConnStr = "https://sab/sites/DevT";
Uri oUri = null;
oUri = new Uri(sConnStr + "/_api/contextinfo");
HttpWebRequest oWebRequest = HttpWebRequest.Create(oUri) as HttpWebRequest;
oWebRequest.UseDefaultCredentials = true;
oWebRequest.Method = "POST";
oWebRequest.Accept = "application/json;odata=verbose";
oWebRequest.ContentLength = 0;
oWebRequest.ContentType = "application/json";
string sResult;
WebResponse sWebReponse = oWebRequest.GetResponse();
using (StreamReader sr = new StreamReader(sWebReponse.GetResponseStream()))
{
sResult = sr.ReadToEnd();
}
var jss = new JavaScriptSerializer();
var val = jss.Deserialize<Dictionary<string, object>>(sResult);
var d = val["d"] as Dictionary<string, object>;
var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
sFormDigest = wi["FormDigestValue"].ToString();
return sFormDigest;
}
You could use Add-in authentication to access SharePoint data.
You could check my test demo below.
https://social.msdn.microsoft.com/Forums/office/en-US/d33f5818-f112-42fb-becf-3cf14ac5f940/app-only-token-issue-unauthorized-access?forum=appsforsharepoint
I want to add Employee on BamBhooHr using Bambhoohr REST API in MVC C#.
I have tried 2 content types to post as shown in the code but not succeed.
1==>
public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
{
var _resultModel = new BBHEmployee();
var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
var _url = $"{_bambhoohrApi}";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
var base64encodedData = System.Convert.ToBase64String(plainTextBytes);
using (var _client = new HttpClient())
{
var _postData = new Dictionary<string, string>
{
{ "firstName", fn },
{ "lastName", ln }
};
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);
var _response = await _client.PostAsync(_url, new FormUrlEncodedContent(_postData));
var _content = await _response.Content.ReadAsStringAsync();
_resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
}
return Json(_resultModel, JsonRequestBehavior.AllowGet);
}
2==>
public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
{
var _resultModel = new BBHEmployee();
var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
var _url = $"{_bambhoohrApi}";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
var base64encodedData = System.Convert.ToBase64String(plainTextBytes);
using (var _client = new HttpClient())
{
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);
_client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var jsonString = "{\"firstName\":\"" + fn + "\",\"lastName\":\"" + ln + "\"}";
StringContent _contt = new StringContent(jsonString, Encoding.UTF8, "application/json");
var _response = await _client.PostAsync(_url, _contt);
var _content = await _response.Content.ReadAsStringAsync();
_resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
}
return Json(_resultModel, JsonRequestBehavior.AllowGet);
}
with both ways, it returns StatusCode 400(BadRequeest)
in that case, this BambhooHr API endpoint requires XML data to post,
so I use this and it's working fine.
var xmlString = "<employee><field id = \"firstName\">"+fn+"</field><field id = \"lastName\">"+ln+"</field></employee>";
var _contt = new StringContent(xmlString,Encoding.UTF8, "text/xml");
var _response = await _client.PostAsync(_url, _contt);
I am trying to make a post request to yobit api in UWP platform,this codes are working for other platforms.Here are my codes-
public async Task<RootObject> sellLimitCode()
{
RootObject track = null;
try
{
string url = "https://yobit.net/tapi/";
string parameters = "method=Trade&pair=ltc_btc&type=buy&rate=1&amount=1&nonce=" + (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
String strMsg = "api secret";
var uriBytes = encoding.GetBytes(parameters);
var uriBytes1 = encoding.GetBytes(strMsg);
string str_alg_name = MacAlgorithmNames.HmacSha512;
MacAlgorithmProvider obj_mac_prov = MacAlgorithmProvider.OpenAlgorithm(str_alg_name);
IBuffer buff_msg = CryptographicBuffer.CreateFromByteArray(uriBytes);
IBuffer buff_key_material = CryptographicBuffer.CreateFromByteArray(uriBytes1);
CryptographicKey hmac_key = obj_mac_prov.CreateKey(buff_key_material);
IBuffer hmac = CryptographicEngine.Sign(hmac_key, buff_msg);
byte[] digest = hmac.ToArray();
string hashText = byteToString(digest);
StringBuilder hex1 = new StringBuilder(hashText.Length * 2);
foreach (byte b in digest)
{
hex1.AppendFormat("{0:x2}", b);
}
string sign1 = hex1.ToString();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Key"] = "api key";
httpWebRequest.Headers["Sign"] = sign1;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{ }
return track;
}
But I am getting Success:0,invalid key,method or nonce.I have tried changing everything.Still not working.
I'm trying to make web requests programmatically in ASP.NET, using the POST method.
I'd like to send POST parameters with the web request as well. Something like this:
LoginData obj = new LoginData();
obj.OSVersion = deviceInformation.OperatingSystem;
obj.DeviceModel = deviceInformation.FriendlyName;
string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
HttpWebRequest GETRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
GETRequest.Method = "POST";
GETRequest.ContentType = "application/x-www-form-urlencoded";
GETRequest.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
//GETRequest.Parameters.add(obj);
Obviously, the commented line does not work. How do I achieve this?
How to get a response by sending my obj as params?
Thanks in advance,
Hemanth.
You need to use theGetRequestStream() method belonging to the HttpWebRequest
void Main()
{
LoginData obj = new LoginData
{
Username = "foo",
Password = "Bar"
};
byte[] objBytes = Encoding.UTF8.GetBytes(obj.ToString());
// obj.OSVersion = deviceInformation.OperatingSystem;
// obj.DeviceModel = deviceInformation.FriendlyName;
string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
request.ContentLength = objBytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(objBytes, 0, objBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
public class LoginData
{
public string Username { get; set; }
public string Password { get; set; }
public string OSVersion { get; set; }
public string DeviceModel { get; set; }
public override string ToString()
{
var temp = this.GetType()
.GetProperties()
.Select(p => $"{p.Name}={HttpUtility.UrlEncode(p.GetValue(this).ToString())}");
return string.Join("&", temp);
}
}
If you want to use HttpClient:
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://XXXXXXXXX.azure-mobile.net/user/logsuserin");
request.Headers.Add("applikationKey", "UFakeKkrayuAeVnoVAcjY54545455544");
request.Content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("OSVersion", deviceInformation.OperatingSystem),
new KeyValuePair<string, string>("DeviceModel", deviceInformation.FriendlyName),
});
var response = client.SendAsync(request).GetAwaiter().GetResult();
}
You can dynamically generate a FORM with "NameValueCollection". Using "NameValueCollection" you can add number of objects to be posted as -
NameValueCollection FormFields = new NameValueCollection();
FormFields.Add("abc", obj1);
FormFields.Add("xyz", obj2);
Response.Clear();
Response.Write("<html><head>");
Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
for (int i = 0; i < FormFields.Keys.Count; i++)
{
Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", FormFields.Keys[i], FormFields[FormFields.Keys[i]]));
}
Response.Write("</form>");
Response.Write("</body></html>");
Response.End();
OnLoad() of this form you can POST to desired URL.
I am doing post and get response using HttpClient to communicate with REST API as below:
public static string PostToAPI( string value)
{
var payload = new APIModel
{
CommandText = value
};
var stringPayload = JsonConvert.SerializeObject(payload);
var httpContent = new StringContent(stringPayload,Encoding.UTF8,"application/json");
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage message=client.PostAsync("https://testAPI/test",httpContent).Result if (message.IsSuccessStatusCode)
{
string result = message.Content.ReadAsStringAsync().Result;
return result;
}
return string.Empty;
}
is there any other alternative or best way do it?
You can always use HttpWebRequest and HttpWebResponse. Try Below
try
{
var webAddr = "URL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application";
httpWebRequest.Method = "POST";
string str = "request string";
httpWebRequest.Headers["Authorization"] = "";
httpWebRequest.Headers["TenantId"] = "";
httpWebRequest.Headers["Client-Type"] = "";
httpWebRequest.Headers["Protocol"] = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
Console.WriteLine(str);
streamWriter.Write(str);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine("result=" + result);
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}