404 error when trying to upload crash to hockeyapp - c#

I'm trying to upload crash manually to HockeyApp using public API. When calling the api link using Postman and uploading crash.log file it works fine but when I try to do the same from C# code I get 404 error.
Here is my code:
string log = ""; //log content
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
var content = new MultipartFormDataContent();
var stringContent = new StringContent(log);
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");
content.Add(stringContent, "log", "crash.log");
var response = await this.client.PostAsync("https://rink.hockeyapp.net/api/2/apps/[APP_ID]/crashes/upload", content);
}
I was using WireShark to analyse the request that Postman is sending and tried to make mine look exactly the same. The only difference I see is that request from C# code has filename* field in Content-Disposition for the attachment while the one from Postman doesn't:
Content-Disposition: form-data; name="log"; filename="crash.log"; filename*=utf-8''%22crash.log%22
It might be worth mentioning that the code is written in portable library in Xamarin project.

Following #Lukas Spieß sugestion I asked the question on HockeyApp support. Apparently they don't handle quotes in the boundary header. The one thing I missed comparing Postman request and mine.
Here is the solution:
var contentTypeString = content.Headers.ContentType.ToString().Replace("\"", "");
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", contentTypeString);

Related

Replicate POSTMAN GET request in C#/VB.net with Authorization

I've been here for 2 days now driving me nuts.
All I want to do it call a webservice at:
https://use-land-property-data.service.gov.uk/api/v1/datasets
Which returns some JSON object.
It requires the "Authorization" header to be set with an API Key that I have.
I've tried it in POSTMAN and it works.
However trying to get a Webclient or Httpclient version working is currently beyond me. I've tried countless examples here on SO. None return the same responses as POSTMAN. All return "Request Rejected"
e.g.
Using client = New HttpClient()
client.DefaultRequestHeaders.Add("Authorization", "MYKEY")
Dim response = Await client.GetStringAsync("https://use-land-property-data.service.gov.uk/api/v1/datasets")
Return response
End Using
what is the equivalent in httpclient to replicate the postman Authorization header?
Try:
httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", "Your Key")

WebRequest returns unreadable string [duplicate]

I'm trying to download an html document from Amazon but for some reason I get a bad encoded string like "��K��g��g�e".
Here's the code I tried:
using (var webClient = new System.Net.WebClient())
{
var url = "https://www.amazon.com/dp/B07H256MBK/";
webClient.Encoding = Encoding.UTF8;
var result = webClient.DownloadString(url);
}
Same thing happens when using HttpClient:
var url = "https://www.amazon.com/dp/B07H256MBK/";
var httpclient = new HttpClient();
var html = await httpclient.GetStringAsync(url);
I also tried reading the result in Bytes and then convert it back to UTF-8 but I still get the same result. Also note that this DOES NOT always happen. For example, yesterday I was running this code for ~2 hours and I was getting a correctly encoded HTML document. However today I always get a bad encoded result. It happens every other day so it's not a one time thing.
==================================================================
However when I use the HtmlAgilitypack's wrapper it works as expected everytime:
var url = "https://www.amazon.com/dp/B07H256MBK/";
HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument doc = htmlWeb.Load(url);
What causes the WebClient and HttpClient to get a bad encoded string even when I explicitly define the correct encoding? And how does the HtmlAgilityPack's wrapper works by default?
Thanks for any help!
I fired up Firefox's web dev tools, requested that page, and looked at the response headers:
See that content-encoding: gzip? That means the response is gzip-encoded.
It turns out that Amazon gives you a response compressed with gzip even when you don't send an Accept-Encoding: gzip header (verified with another tool). This is a bit naughty, but not that uncommon, and easy to work around.
This wasn't a problem with character encodings at all. HttpClient is good at figuring out the correct encoding from the Content-Type header.
You can tell HttpClient to un-zip responses with:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip,
};
using (var client = new HttpClient(handler))
{
// your code
}
This will be set automatically if you're using the NuGet package versions 4.1.0 to 4.3.2, otherwise you'll need to do it yourself.
You can do the same with WebClient, but it's harder.

Issue while creating product using Shopify API

I am experiencing a weird issue while exporting some products to Shopify. When I save a JSON generated using JSON.net to txt file and then read it and then send it to Shopify's create product API, it works fine. However, if I just save the JSON to string and send post request directly, I get a 502 gateway error from Shopify. This happens only when creating certain products, where the JSON payload is somewhat bigger than normal. On other products, just saving JSON to a string and then sending to Shopify works OK. Weirdly, when I save the JSON to file from C#, then read that file a few lines below in the same code, and use that content as JSON string and send a post request, it again doesn't work. What do you think could be the issue?
Here's the JSON generated using JSON.net which works OK when read from file (https://pastebin.com/9SKFPjGJ)
var jsonContent = JsonConvert.SerializeObject(myObject);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, $"https://{shopifySlug}.myshopify.com/admin/products/{originalShopifyProductId}.json"))
{
requestMessage.AddShopifyHeaders(shopifyAccessToken); // just a method for adding necessary shopify headers
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
response = await client.SendAsync(requestMessage);
}
Its getting hard for me to know the reason.
Here's what works:
Code that works:
json.txt was generated using this separately:
System.IO.File.WriteAllText("E:\\json.txt",JsonConvert.SerializeObject(myObject));
(Note that if the above line of code is inserted before the code below in the same file, then the code below doesn't work, i.e. the file has to be saved separately for it to work).
And then, just reading the JSON from file and sending that in the POST request works. Code below:
var jsonContent = System.IO.File.ReadAllText("E:\\json.txt");
using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, $"https://{shopifySlug}.myshopify.com/admin/products/{originalShopifyProductId}.json"))
{
requestMessage.AddShopifyHeaders(shopifyAccessToken); // just a method for adding necessary shopify headers
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
response = await client.SendAsync(requestMessage);
}
Also the not working code at the very top works OK for smaller JSON payloads like this one https://pastebin.com/RhYjVuvv

Posting Soap XML in Windows 8 Metro App - Errors

I am writing C# code for a WinRT Surface Tablet in Visual Studio Express 2012 for Windows 8. Although my xml is formatted (I am porting from apps on other platforms that work fine) I am apparently having trouble with the request syntax.
I've been trying several different approaches and hit dead ends with the limitation of windows store apps in methods. The last I have tried is using HttpClient, HttpContent and HttpRequestMessage: (omitting the actual xml and urls, obviously)
string xmlSOAP = "..............[my soap xml]................."
string url = "http://example.domain.com/myMagicalwebservice.asmx"
string SOAPAction = "www.blahblah.com/doXMLStuff";
HttpClient hc = new
HttpContent content = new String Content(xmlSOAP);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
req.Headers.Add("SOAPAction", SOAPAction);
req.Method = HttpMethod.Post;
req.Content = content;
req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/soap+xml;charset=UTF-8");
hc.SendAsync(req).ContinueWith(responseTask =>
{
System.Diagnostics.Debug.WriteLine(responseTask.Result);
});
This results in a System.FormatException of "The format of value 'application/soap+xml;charset=UTF-8' is invalid."
If I instead add the content type directly to the HttpContent instead of to HttpRequestMessage, I get the same outcome.
If I simply comment out the line adding the content type (just doing dumb trial and error here) I receive a result with statuscode 415: "Unsupported Media Type."
I have tried posting using the PostAsync method of HttpClient but I am unsure how to get the response using that.
Any help would be very much appreciated, and I thank you in advance for your time!
Try this:
req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/soap+xml;charset=UTF-8");

Error posting a share on LinkedIn using Hammock lib

I'm trying to send a new Share on a Linkedin Person. This is my client code:
RestClient client = new RestClient()
{
Authority = "http://api.linkedin.com/v1",
Credentials = this.AccessCredentials(connectionData.ApplicationKey, connectionData.ApplicationSecret, connectionData.AccessToken, connectionData.AccessSecret),
Method = WebMethod.Post,
Encoding = Encoding.UTF8,
};
RestRequest request = new RestRequest()
{
Path = "people/~/shares",
Encoding = Encoding.UTF8,
};
Share share = new Share(socialMessage.Text, socialMessage.Name, socialMessage.Description, VisibilityCode.Anyone);
share.Content.SubmittedImageUrl = socialMessage.PictureLink;
share.Content.SubmittedUrl = socialMessage.Link;
String content = Utilities.SerializeToXml<Share>(share);
client.AddPostContent(System.Text.Encoding.UTF8.GetBytes(content));
client.AddHeader("Content-Type", "text/xml");
request.AddPostContent(System.Text.Encoding.UTF8.GetBytes(content));
request.AddHeader("Content-Type", "text/xml");
RestResponse response = client.Request(request);
I always obtain this error message after the call "Couldn't parse share document: error: Unexpected end of file after null".
Does anyone can tell me how to use Hammock library to send a POST to LinkedIn?
Thanks & Regards
Also there is possible solution here:
https://github.com/danielcrenna/hammock/issues/4
I'm not sure how to use the hammock library, but you can debug API calls for LinkedIn (or any other web service) using the tips at
http://developer.linkedin.com/documents/debugging-api-calls
This will show you how to install an HTTP sniffer and watch the traffic to see what's happening. Once you've done that, if you're still having issues post them and it'll be possible to debug what's going wrong.

Categories