Getting redirect link using HTTPClient post - c#

I'm trying to find the redirect url using the headers, so I googled around and found a few examples:
Header[] arr = httpResponse.getHeaders("Location");
for (Header head : arr){
String whatever = arr.getValue();
}
AND
HttpPost request1 = new HttpPost("https://hrlink.healthnet.com/");
HttpResponse response1 = httpclient.execute(request1);
// expect a 302 response.
if (response1.getStatusLine().getStatusCode() == 302) {
String redirectURL = response1.getFirstHeader("Location").getValue();
// no auto-redirecting at client side, need manual send the request.
HttpGet request2 = new HttpGet(redirectURL);
HttpResponse response2 = httpclient.execute(request2);
... ...
}
Where they get "Location" from header, however I am not able to pull the "Location" out of the HttpResponseMessage from my version, I tried moving things here and there but it does not contain the method to accept the parameter, how am I able to get the redirect URL using httpClient?
var client = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", "---"),
new KeyValuePair<string, string>("password", "---")
};
var content = new FormUrlEncodedContent(pairs);
var response = client.PostAsync(uri, content).Result;
HttpHeaders headerlist = response.Headers;
foreach (var header in headerlist)
{
//Red line on header("Location")
label1.Text += header("Location") + "\n";
}

Just for test, with www.google.com you can test redirection:
var request = (HttpWebRequest) WebRequest.Create("http://www.google.com");
request.AllowAutoRedirect = false;
using (var response = (HttpWebResponse) request.GetResponse())
{
string location = response.Headers["Location"];
Console.WriteLine(location);
}

Related

Postman form-data: How to program it inside a HttpRequestMessage?

I am doing a request through postman to a specific url but I set the form-data type in order to get data to the site like this:
Now I want to program this request inside C# but everything I tried so far is returning a 400 Bad Request response. This is what I tried:
public async Task<CheckAccessTokenModel> CheckAccessTokenAsync(string accessToken)
{
string uriString = "someurl";
var uri = new Uri(uriString);
try
{
using(var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = uri
};
var ClientId = ConfigurationAccessor.Configuration["WebCredentials:ClientId"];
var Secret = ConfigurationAccessor.Configuration["WebCredentials:Secret"];
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ClientId}:{Secret}"));
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authString);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent("token"), accessToken);
request.Content = content;
var response = await httpClient.SendAsync(request);
var checkTokenResponseData = await response.Content.ReadAsStringAsync();
//return new CheckAccessTokenModel { Active = true, Exp = 1647431224233 };
return JsonConvert.DeserializeObject<CheckAccessTokenModel>(checkTokenResponseData);
}
}
catch
{
return null;
}
}
I am doing it with the MultipartFormDataContent Object as suggested by many others here but it still won't work.
What can be the problem here?
EDIT: Wrong picture replaced
You can simply
request.Content = new StringContent($"token={accessToken}");
With form data I think it's something like this:
var data = new Dictionary<string, string>
{
{"token", acccessToken}
};
using var content = new FormUrlEncodedContent(data);
request.Content = content;

Bitstamp API POST request with parameters

please, help me with POST api request in C#.I dont know how to correctly send parameters „key“, „signature“ and „nonce“ in POST request. It constantly tells me "Missing key, signature and nonce parameters“.
HttpWebRequest webRequest =(HttpWebRequest)System.Net.WebRequest.Create("https://www.bitstamp.net/api/balance/");
if (webRequest != null)
{
webRequest.Method = HttpMethod.Post;
webRequest.ContentType = "application/json";
webRequest.UserAgent = "BitstampBot";
byte[] data = Convert.FromBase64String(apisecret);
string nonce = GetNonce().ToString();
var prehash = nonce + custID + apikey;
string signature = HashString(prehash, data);
body = Serialize(new
{
key=apikey,
signature=signature,
nonce=nonce
});
if (!string.IsNullOrEmpty(body))
{
var data1 = Encoding.UTF8.GetBytes(body);
webRequest.ContentLength = data1.Length;
using (var stream = webRequest.GetRequestStream()) stream.Write(data1, 0, data1.Length);
}
using (Stream s = webRequest.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
contentBody = await sr.ReadToEndAsync();
return contentBody;
}
}
}
The "Request parameters" as Bitstamp specifies in the docs is actually supposed to be sent with content type "application/x-www-form-urlencoded" instead of "application/json".
I would also use HttpClient to perform the post as that has a much more simple setup to perform Http requests
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key", apikey),
new KeyValuePair<string, string>("signature", signature),
new KeyValuePair<string, string>("nonce", nonce)
});
var result = await client.PostAsync("https://www.bitstamp.net/api/balance/", content);
string resultContent = await result.Content.ReadAsStringAsync();
}

Posting unicode data using HttpClient

I am trying to post some unicode data using Http request message. Somehow content encoding is causing some issue. I am not setting any encoding explicitly in my code.
For example, I am trying to send 'รัค' & on client side it is being received as 'รัà¸'.
Sample code
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer, })
using(var httpClient = new HttpClient(handler)){
//set all cookies
foreach (var obj in configurationData["request_cookies"])
{
var cookie = ((JProperty)(obj));
cookieContainer.Add(new Uri(configurationData["request_cookie_base_url"].ToString()),
new Cookie(cookie.Name, HttpUtility.UrlEncode(cookie.Value.ToString())));
}
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(configurationData["form_url"].ToString());
//set all request headers
foreach (var obj in configurationData["request_headers"])
{
var cookie = ((JProperty) (obj));
request.Headers.Add(cookie.Name, cookie.Value.ToString());
}
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
//get request content data from configurationData as keyvalue pair
var contentValue = parsedCrmConfigurationData["form_data_template"]
.ToObject<Dictionary<string, string>>();
request.Content = new FormUrlEncodedContent(contentValue);
var response = httpClient.SendAsync(request).Result;
response.EnsureSuccessStatusCode();
}
Do I need to pass encoding specifically? if yes then how?
Please help me understand the issue.
you can use below code to encode your content
private static HttpContent getencodedContent(string jsonString)
{
var cont = new StringContent(jsonString, Encoding.UTF8, "application/json");
return cont;
}

Simplest way to call REST

I have call to REST service from jscript that works fine:
post('/MySite/myFunct', { ID:22 })
How to make this call from C# in most native c# way?
UPD:
I need HTTPS solution also.
UPD:
And I need to use cookies
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "ID", "22" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com", content);
var responseString = await response.Content.ReadAsStringAsync();
Old traditional way is using HttpClient / HttpWebRequest.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/Test/TestPostData");
request.Method = "POST";
SampleModel model = new SampleModel();
model.PostData = "Test";
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(model);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Apart from this I prefer more Restclient /Restsharp from nuget.
A simple example of post request will be like this
using RestSharp;
using RestTest.Model;
private void button1_Click(object sender, EventArgs e)
{
var client = new RestClient();
var request = new RestRequest();
request.BaseUrl = "http://carma.org";
request.Action = "api/1.1/searchPlants";
request.AddParameter("location", 4338);
request.AddParameter("limit", 10);
request.AddParameter("color", "red");
request.AddParameter("format", "xml");
request.ResponseFormat = ResponseFormat.Xml;
var plants = client.Execute<PowerPlantsDTO>(request);
MessageBox.Show(plants.Count.ToString());
}
You can use HTTP Verbs directly from call
A Post example:
public void Create(Product product)
{
var request = new RestRequest("Products", Method.POST); < ----- Use Method.PUT for update
request.AddJsonBody(product);
client.Execute(request);
}
A Delete Example
public void Delete(int id)
{
var request = new RestRequest("Products/" + id, Method.DELETE);
client.Execute(request);
}
For adding header in request
request.AddHeader("data", "test");
A Get Request
private RestClient client = new RestClient("http://localhost:8080/api/");
RestRequest request = new RestRequest("Products", Method.GET);
RestResponse<YourDataModel> response = client.Execute<YourDataModel>(request);
var name = response.Data.Name;

400 Bad Request C# Microsoft Face Api

I am trying to get simple functionality from the Microsoft Face API, using this example provided (link):
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "{string}";
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{body}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
response = await client.PostAsync(uri, content);
}
Whenever I execute the code, I get a 400 bad request, of which I cannot how to view the specific cause. This is how mine looks:
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxxxxxxxxxxxxxxxxxxxxxx");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "Age";
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{ \"url\":\"http://i0.kym-cdn.com/photos/images/newsfeed/000/272/907/dc1.jpg/ \"}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
Console.Write(response.StatusCode);
}
The code looks fine and the only issue I see is that your image is not accessible. I am getting access denied error, if I try to access the image directly via browser. Is that something you have checked?
I tried the below code and it works fine:
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key","please use your key");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "age";
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("{ \"url\":\"https://lh5.googleusercontent.com/-AI__M0nZDU4/AAAAAAAAAAI/AAAAAAAAAGs/P5tdI3rFaFs/s0-c-k-no-ns/photo.jpg \"}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
Console.Write(response.StatusCode);
}

Categories