Let me start by showing code:
private async Task<bool> session()
{
string post = " ";
HttpContent postContent = new StringContent(
post,
Encoding.ASCII,
"application/x-www-form-urlencoded");
using (HttpResponseMessage response = await this.httpClient.PostAsync(
"CANT_SHARE_URL.com/data", postContent))
using (HttpContent content = response.Content)
{
this.session =content.Headers.GetValues("session").FirstOrDefault();
}
return true;
}
I can't disclose the url.
The problem is that it does not set the session variable and the content has returned the headers the header is also showing up in fiddler. The exception 'System.InvalidOperationException' I've tried most obvious options it's certainly responding correctly and I somehow got the headers into a string but I can't remember how.
Are you sure the session header is on the Content? Have you tried looking in the request.Headers collection?
Related
1
Hi so I want to display the response of the website in this panel, How would I go about that. I have the necessary System.Net Etc. Heres the code:
private void panel7_Paint(object sender, PaintEventArgs e)
{
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
}
Would I need to set the webresponse as a string and than pass it as string tx?
[The code of said panel]
the code of the panel in cs
[3]: https://i.stack.imgur.com/DBY9w.png //the panel I want the data to display.
I believe you need a label in the panel, then change its label.Text property to the response body.
To read the response body from an HttpWebResponse, please refer to this answer.
I'd also suggest you switch to the modern HttpClient API if you use .NET Core 3 or above:
using var httpClient = new HttpClient();
Example:
using var httpRequest = new HttpRequestMessage(HttpMethod.Get, "http://www.contoso.com/default.html");
using var httpResponse = await httpClient.SendAsync(httpRequest);
label.Text = await httpResponse.Content.ReadAsStringAsync();
Or even simpler, if you don't need to edit the request message at all:
label.Text = await httpClient.GetStringAsync("http://www.contoso.com/default.html");
I have this code below code to create a database in couchDB:
private async void DatabaseCreate()
{
if (!await DatabaseExist())
{
var contents = new StringContent("", Encoding.UTF8, "text/plain");
this.uri = "http://USER:PASSWORD#localhost:5984/item_sn";
var response = await client.PutAsync(this.uri, contents); //set the contents to null but same response.
Console.WriteLine(response.Content.ReadAsStrifngAsync().Result);
}
}
My problem is that it is giving me a response with StatusCode:401, saying "Unauthorized". I tried curling it in the terminal and it gives me a successful response. Is there some preconditions I need to set for the httpclient? Or am I using the wrong method. I know there are some third party package for couchDB but for my case I just want to use C#'s httpclient.
Thanks in advance
curl command:
curl -X PUT http://USER:PASSWORD#localhost:5984/item_sn
Looks like in HttpClient class you can include credentials with HttpClientHandler Class with its Credentials property. Take a look at this answer. Try it, maybe that would work.
Here's the code that worked.
public async void DatabaseCreate()
{
if (!await DatabaseExist())
{
var contents = new StringContent("", Encoding.UTF8, "text/plain");
var byteArray = Encoding.ASCII.GetBytes("user:pass");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(byteArray));
this.uri = "http://localhost:5984/databasename";
var response = await client.PutAsync(this.uri, contents);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
}
Currently trying to do a Get request as part of a c# program. The request works fine on Postman as it uses a header for authorization. However I cannot get the code working for the program to use this header correctly in its Get request. I've had a good look around and tried various bits of code I've found but haven't managed to resolve it so any help would be appreciated!
public string Connect()
{
using (WebClient wc = new WebClient())
{
string URI = "myURL.com";
wc.Headers.Add("Content-Type", "text");
wc.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";//this is the entry code/key
string HtmlResult = wc.DownloadString(URI);
return HtmlResult;
}
}
Above is one method inside the class.
Below is another attempt which is an extension method that gets passed the URL:
public static string GetXml(this string destinationUrl)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(destinationUrl);
request.Method = "GET";
request.Headers[HttpRequestHeader.Authorization] = "Bearer
OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new
StreamReader(responseStream).ReadToEnd();
return responseStr;
}
else
{
Console.Write(String.Format("{0}({1})",
response.StatusDescription, response.StatusCode));
}
return null;
}
Might I recommend the very handy RestSharp package (find it on Nuget).
It turns your current code into something like
public string Connect()
{
var client = new RestClient();
var request = new RestRequest("myURL.com", Method.GET);
request.AddParameter("Authorization", "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3");
var response = client.Execute(request);
return response.Content;
}
It's much more succinct and easier to use (in my opinion) and thus lessens the likelihood of passing in or using incorrect methods.
If you're still having issues getting data back/connecting. Then using PostMan click Code in the upper right of PostMan and select the C# (RestSharp) option. Whatever is generated there matches exactly what PostMan is sending. Copy that over and you should get data back that matches your PostMan request.
If this is a duplicate of any existing question, please let me know which post has a similar situation.
I am trying to call a POST API, which actually works perfectly from REST clients like POSTMAN.
When I try to call that API from C# using HttpClient, it only works if I do not use any HTML content in the request body.
Here is my code:
HttpClient client = new HttpClient();
string baseUrl = channel.DomainName;
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders
.TryAddWithoutValidation(
"Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
const string serviceUrl = "/api/create";
var jsonString = CreateApiRequestBody(model, userId, false);
var uri = new Uri(baseUrl + serviceUrl);
try
{
HttpResponseMessage response = await client.PostAsync(uri.ToString(), new StringContent(jsonString, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
Stream receiveStream = response.Content.ReadAsStreamAsync().Result;
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var str = readStream.ReadToEnd();
}
...
}
And my jsonString looks like:
{
\"user_id\":\"6\",
\"description\":\"<h2 style=\\\"font-style:italic;\\\"><u><font><font>Test Test Test </font></font></u></h2>\\n\\n<p style=\\\"font-style: italic;\\\">Hi it's a Test JOB</p>\\n\\n<p> </p>\"
}
When I use plain text in description tag, the API returns a valid response, but not with the HTML content in it.
I believe I might be missing some extra header or something else.
Any help will be greatly appreciated.
Have you tried using WebUtility.HtmlEncode() method?
Where you're setting the StringContent content, try using WebUtility.HtmlEncode(jsonString) to make it API-friendly.
Like this:
using System.Net;
HttpResponseMessage response =
await client.PostAsync(
uri.ToString(),
new StringContent(WebUtility.HtmlEncode(jsonString),
Encoding.UTF8,
"application/json"));
Don't forget to use System.Net
That will give you a safe (especially for APIs) HTML string to use in your request.
Hope this helps.
Quite a simple problem I've got that would be easy to solve I reckon for the brains. It's just a tried a different queries on Google and nothing popped up but hey that's why I am here.
Here is the error:
System.InvalidOperationException
Basically this error is thrown on this piece of code here
string test = response.Content.Headers.GetValues("Location").FirstOrDefault();
Location in Fiddler looks like this:
Location: https://www.redirecturlishere.com/blah
Here is the entire function:
private async Task<string> GetRequest()
{
//HttpContent postContent = new StringContent(post, Encoding.ASCII, "application/x-www-form-urlencoded");
using (HttpResponseMessage response = await httpClient.GetAsync(
"http://www.cant-share-url.com"))
{
using (HttpContent content = response.Content)
{
string test = response.Content.Headers.GetValues("Location").FirstOrDefault();
}
}
return "";
}
More details on the error, "Additional information: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."
I don't think there is much else to explain so I'll leave it at that.
I have solved the problem basically the header was not stored in the content, silly me.
And for anyone who doesn't see the solution. :)
string test = response.Headers.GetValues("Location").FirstOrDefault()