I am using Thumbor as Docker image on my PC. I am able to save the image to Thumbor but I am not able to read the image from URL
This is the method I am using to save the file
var httpClient = new HttpClient();
var httpContent = new ByteArrayContent(FileToByteArray(filename));
HttpResponseMessage response = null;
try
{
httpContent.Headers.Add("Content-Type", "image/jpg");
response = httpClient.PostAsync("http://localhost:32773/image", httpContent).Result;
}
catch (HttpRequestException ex)
{
}
And I am using this URL from the postman and it throws an error 400Bad Request
http://localhost:32773/1.jpg
Am I missing something in the URL? Can anyone help me with a sample C# code? appreciate your help!
The correct request URL is:
http://localhost:32773/image/<the original location response>
Here is an example of storing an image
POST http://192.168.2.48:8082/image
HTTP/1.1 201 Created
Date: Thu, 05 Mar 2020 11:56:12 GMT
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Location: /image/8ad1c65a3e6341cfb231b1faf438fc0e/image.jpg
Server: TornadoServer/4.5.3
Fetching the same image:
GET http://192.168.2.48:8082/image/8ad1c65a3e6341cfb231b1faf438fc0e/image.jpg
In short: make sure you store the Location information from the response header when storing an image
Related
I have a problem when I´m trying sending post and put requests to my webapi (the server side is coded in php and works with mysql).
If I try to send a get request there is no problem at all, the API responds properly, the problem comes when I try to send a body in request (that´s why I think post and put fails).
I am sure that my api works well, as long as I have done tests with postman and another clients and they all follow a correct way with these requests.
The API responds 400 Bad Request and I don´t know what to do. I´ve done the same api coded in C# and my code in client-side works, there´s any incompatibility between Universal Windows Platform and PHP API´s?
My PUT method:
public async Task<int> updateFestivalDAL(Festival festival)
{
int resultado = 0;
Uri miConexion = (new clsMyConnection().getConnection());
HttpClient miCliente = new HttpClient();
String body = "";
HttpStringContent contenido;
HttpResponseMessage miRespuesta = new HttpResponseMessage();
try
{
body = JsonConvert.SerializeObject(festival);
contenido = new HttpStringContent(body, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
miRespuesta = await miCliente.PutAsync(new Uri(miConexion + "/" + festival.ID), contenido);
if (miRespuesta.IsSuccessStatusCode)
{
resultado = 1;
}
}
catch (SqlException e)
{
throw e;
}
return resultado;
}
That´s my body in request:
"{\"ID\":1,\"edicion\":\"Prueba año anterior\",\"nombre\":\"fgh\",\"fecha_inicio\":\"2017-10-01T00:00:00\",\"fecha_fin\":\"2017-10-03T00:00:00\",\"coordenadas\":\"asdf\",\"twitter\":\"\",\"facebook\":\"\",\"instagram\":\"\",\"web\":\"\",\"curiosidades\":\"\"}"
And that´s my API response (miRespuesta variable value):
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 2, Content:
Windows.Web.Http.HttpStreamContent, Headers:
{
Connection: close
Server: Apache/2.4.34 (Win32) OpenSSL/1.0.2o PHP/5.6.38
Date: Wed, 31 Oct 2018 21:47:36 GMT
X-Powered-By: PHP/5.6.38
}{
Content-Length: 0
Content-Type: text/html; charset=UTF-8
}}
Please help me if you know something.
UPDATE: When I see content of miCliente variable (the one with httpclient), I can see there´s a list element called DefaultRequestHeaders. Maybe there´s the problem? I have to edit these to make them compatible with PHP?
UPDATE 2:
I´ve changed two dates elements (fecha_inicio, fecha_fin) in database and my Festival class, so they are now varchar (string at class), trying if the problem was parsing datetimes and try saving as date in database, but still not work.
Postman successfully request:
PUT /festival/1 HTTP/1.1
Host: notrelevantbutwellformed.com
Content-Type: application/json
cache-control: no-cache
Postman-Token: 100313d6-7087-4712-8b93-17873e1db14b
{
"ID": "1",
"edicion": "fgh",
"nombre": "fgh",
"fecha_inicio": "2018-11-01",
"fecha_fin": "2018-11-01",
"coordenadas": "asdf",
"twitter": "asfd",
"facebook": "ffsd",
"instagram": "asrss",
"web": "noo va a petar",
"curiosidades": "sdfsdfdsf",
"url_logo": "",
"url_cartel": ""
}------WebKitFormBoundary7MA4YWxkTrZu0gW--
I have built a small windows forms application just to play around with image recognition. I have trained a model, and I have built a windows forms application that takes my webcam image stream, uploads frames as JPG to an AWS S3 bucket, then passes the publicly readable URL to the Vision API to provide scoring on the tags.
If I pass the image via a POSTMAN call, it works fine, however within my code, I get the following error:
{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
apim-request-id: 8d5759e5-d32a-4ba2-8b54-16f3a3f1aa40
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
x-content-type-options: nosniff
Date: Thu, 20 Sep 2018 00:49:39 GMT
Content-Length: 116
Content-Type: application/json; charset=utf-8
}}
According to the documentation:
Response 415 Unsupported media type error. "Content-Type" does not
match the post content.
For image URL, "Content-Type" should be application/json For binary
image data, "Content-Type" should be application/octet-stream
As you will see from my code below, I am setting the right content type. I will just post the function dealing with posting to the API as that's where the issue must be. Any help would be appreciated.
Firstly, the evidence that the call via POSTMAN works:
Here is my method that fails. You can see I set the right content type, and I'm using the same images for testing between my code and POSTMAN.
/// <summary>
/// Take a provided image url and return the Vision API results
/// </summary>
/// <param name="url">a valid HTTP or HTTPS url containing a reference to a JPG image</param>
/// <returns></returns>
static async Task<string> GenerateVisionResult(string url)
{
string visionResult = null;
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/3dd9e6c3-aac4-4da1-8c74-cd2d581d4782/url?iterationId=5c1b1548-98d7-45b0-a0e7-f397f35ffcd9");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Prediction-Key", "<redacted for post on StackOverflow>");
var UrlBody = new UrlBody
{
Url = url
};
var httpRequestMessage = new HttpRequestMessage
{
Content = new StringContent(JsonConvert.SerializeObject(UrlBody),Encoding.UTF8),
Method = HttpMethod.Post
};
HttpResponseMessage httpResponse = await client.PostAsync(client.BaseAddress, httpRequestMessage.Content);
if (httpResponse.IsSuccessStatusCode)
{
visionResult = await httpResponse.Content.ReadAsStringAsync();
}
else
{
visionResult = httpResponse.StatusCode.ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return visionResult;
}
EDIT: I think I just realised my mistake, in the way I'm handling adding the url to the POST method. I'll report back once i've tried to fix it.
EDIT2: Nope. Still no dice. I thought maybe I wasn't seralising the URL object correctly, but i've tested and the content is as expected, just serialising the following object:
public class UrlBody
{
public string Url { get; set; }
}
Thanks to Jamie for his help with Fiddler, but I found the issue. You can't pass the content to the POST method the way I have in my original code. You have to convert the content into something that can be passed as HttpContent to the post method, e.g.
var content = JsonConvert.SerializeObject(url);
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Then you will get a valid response.
Use /image/ in the end of URL (Example: "https://....//detect/iterations/Iteration37/image/nostore")
Example postman
Binary
I have an MVC4 WebAPI project and have a controller FileController that has this Get method in it:
public HttpResponseMessage Get(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File Name Not Specified");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = fileService.GetFileStream(id);
if (stream == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File Not Found");
}
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = id;
return response;
}
In the browser going to localhost:9586/File/myfile.mp3it dispatches the file correctly as an attachment and you can save it. If it is an audio file, you can stream it from the HTML5 audio tag.
Now, I need to call this WebAPI method from an MVC4 web app, basically wrapping it. Here it comes:
public HttpResponseMessage DispatchFile(string id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8493/");
HttpResponseMessage response = client.GetAsync("api/File/"+id).Result;
return response;
}
Going to localhost:8493/File/DispatchFile/my.mp3 returns:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache Connection: Close Cache-Control: no-cache Date: Thu, 05 Sep 2013 15:33:23 GMT Server: ASP.NET Server: Development Server: Server/10.0.0.0 X-AspNet-Version: 4.0.30319 Content-Length: 13889 Content-Disposition: attachment; filename=horse.ogg Content-Type: application/octet-stream Expires: -1 }
So it looks like the Content is indeed StreamContent, but it doesn't return it as a saveable file. Now the question is, how to mirror the behavior when calling the API directly? Any suggestions much appreciated.
I believe the use of HttpClient.Result is not the correct approach here. I think you may need to use the 'Content' property and then call ReadAsStreamAsync to get a handle on the file stream that is returned by your WebAPI method. At that point, you should be able to just write this stream to the response stream, allowing the file to be downloaded / audio to be streamed via HTML5.
See here for an example of using HttpClient to get a file (the link shows how to handle large files, but I believe the approach used there is what you will need to do):
http://developer.greenbutton.com/downloading-large-files-with-the-net-httpclient/
I am attempting to set up Log In With Paypal, but I am receiving a Unauthorized Message ("{\"error_description\":\"Unable to generate token\",\"error\":\"access_denied\"}") while obtaining the access token ( I received the authorization code without a hiccup). The only thing I think I might have wrong is the availability of this service to non US residents. It says that REST APIs is not available to non US residents, but I noticed that its segregated from the 'Log In With Paypal'. Does anyone know?
Here is the code I am using too retrieve the access token in case anyone can notice an error:
string TokenEndpoint = "https://api.paypal.com/v1/identity/openidconnect/tokenservice";
System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("client_id", this._clientId);
reqparm.Add("client_secret", this._clientSecret);
reqparm.Add("grant_type", "authorization_code");
reqparm.Add("code", authorizationCode);
reqparm.Add("redirect_uri", HttpUtility.UrlEncode(returnUrl.AbsoluteUri));
try
{
using (WebClient client = new WebClient())
{
var data = client.UploadValues(TokenEndpoint, "POST", reqparm); // Access Denied exception occurs here.
...
Here is the response I receive:
HEADER
{
Pragma: no-cache
Vary: Accept-Encoding
Connection: close
Content-Length: 72
Cache-Control: no-store
Content-Type: application/json
Date: Mon, 10 Jun 2013 23:35:02 GMT
Server: Apache-Coyote/1.1
}
Content
text
{
\"error_description\":\"Unable to generate token\",
\"error\":\"access_denied\"
}"
I'm trying to use HttpClient to read the response content from a 3rd party API (Rackspace Cloud Files). Here's what I have so far. I can't seem to get the content.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Auth_User", username);
client.DefaultRequestHeaders.Add("X-Auth-Key", api);
client.GetAsync("identity.api.rackspacecloud.com".ToAbsoluteUrl()).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<string>().ContinueWith(
(readTask) =>
{
var result = readTask.Result;
});
});
This gives me "No 'MediaTypeFormatter' is available to read an object of type 'String' with the media type 'text/html'." error.
I need to retrieve the response details as noted in the Rackspace docs (example):
HTTP/1.1 204 No Content
Date: Mon, 12 Nov 2007 15:32:21 GMT
X-Storage-Url: https://storage.clouddrive.com/v1/CF_xer7_34
X-CDN-Management-Url: https://cdn.clouddrive.com/v1/CF_xer7_34
X-Auth-Token: eaaafd18-0fed-4b3a-81b4-663c99ec1cbb
Content-Length: 0
Content-Type: text/plain; charset=UTF-8
How do I get the response?
When I use ReadAsStringAsync, it gives my the HTML source of my page.
Thank you.