How to return image/png media type response in Spray? - spray

I want to return image/PNG as response to calling URL. How can I do it in Spray?

This may help:
import java.io._
import spray.http._
import MediaTypes._
sender ! HttpResponse(entity = HttpEntity(`image/png`, HttpData(new File("my.png"))))
See also, HttpMessage, HttpEntity, HttpData and MediaTypes. You can do same for HttpRequest as well. You can use Array[Byte] or ByteString instead of File. Checked for Spray 1.3.x.

Related

How do I send the proper payload through HTTP on iOS shortcuts?

I would like to make a POST request to my website: example: www.example.net.
I got this to work easily on Python, using below code:
import requests
resp = requests.post('http://example.net', data = {'param1': 'information'})
But when I try to implement this in iOS Shortcuts, using the Get Content of URL action, it just times out while waiting for a response.
I have a feeling this has to do with the proper placing of payload, such as the three options: form, JSON, or file.
Does anybody have any advice? Thanks in advance.

FSharp.Data HTTP Utility RequestString response Body is prepended with the word "Text"

I'm making a simple web call (GET) to an api that returns some json. Trouble is, I can't parse it with Newtonsoft (or otherwise) because the HTTP Utility RequestString response.Body is prepended with the word "Text".
Text
"[{"name":"10 Years","desc":"","descData":null,"closed":false ...
What can I do to avoid this and get my json string as an actual json string?
If you take a look at the FSharp.Data Http Utils ResponseBody docs you will notice it returns a Discriminated Union with 2 options.
So you will want to handle it with something like this:
let myHttphandler resp =
match resp with
| Text txt -> txt |> customTextHandler
| Binary bytes -> bytes |> customBytesHandler
Of course, if you know you will always get text, use _ in your DU.
Your customTextHandler function will probably deserialize your json.

Sending post request flutter with specific requirements

I need some suggestion on how to send a POST request using the http module in Flutter with some parameters.
I need to set the username to a string(in the body of the request), and also need to set a property to a FILE in the body.
The easiest way to do requests on Flutter is to use the Dio package
if your json payload is,
{"username":"johndoe", "image":"base64 image data"}
In dio the code looks like
import "dart:io";
import "dart:convert";
import 'package:dio/dio.dart';
// read image bytes from disk as a list
List<int> imageBytes = File("./image.png").readAsBytesSync();
// convert that list to a string & encode the as base64 files
String imageString = base64Encode(imageBytes);
// Send a post request to server
dio.post("/url-to-post-to", data: {"username":"johndoe", "image":imageString});

.net core 2 rejects request with 415 when I set Accept to text/csv

When i POST a request to my .net core 2 mvc backend it returns json data.
I want to optionally change the headers as so , which i will then return a csv file of the data for download
'Accept': 'text/csv',
'Content-Type': `text/csv; charset=utf-8`
I set the controller base class with this Produces filter
[Produces("application/json", "text/csv")]
But those headers always cause .net to return 415 Unsupported Media Type
The controller action looks like this
[HttpPost]
public async Task<IActionResult> Post([FromBody] PostArgs args)
You source of problem is Content-Type: text/csv; charset=utf-8 header.
[FromBody] forces MVC middleware to use the input formatter for model binding (I am talking about PostArgs model). And by default, ASP.NET Core registers only one, JSON input formatter. Cause you set Content-Type, middleware cannot use that default formatter (as Content-Type header says that data in request body should be processed as CSV, not JSON) and so it throws 415 Unsupported Media Type error.
... I want to optionally change the headers as so , which i will then return a csv file of the data for download
Actually, it looks like you understand in wrong way what Content-Type header does:
In requests, (such as POST or PUT), the client tells the server what type of data is actually sent.
In other words, you only need to specify the Accept header, cause
The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals.
And it is the server then, who uses a Content-Type header in responses to tell the client what the content type of the returned content (in response) actually is.
To return csv data, you return a ContentResult rather than a JsonResult object. This allows you to define the Content-Type:
return new ContentResult("csv-data", "text/csv", 200);
If you want to return a physical file you could return a FileResult object.
By default, the Accepts header isn't enforced. You can enforce it via configuration:
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
});
In order to accept additional formats, you'll also need to add InputFormatters:
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
config.InputFormatters.Add(new TextInputFormatter())
config.OutputFormatters.Add(new StringOutputFormatter());
});

MSXML: XMLHTTP doesn't support charset from header

I'm using MSXML2_TLB.pas generated from the Microsoft XML type library to call a pretty simple web-service, so I don't need the full XML wrapping and just do this:
var
r:XMLHTTP;
begin
r:=CoXMLHTTP.Create;
r.open('POST',WebServiceURL,false,'','');
r.setRequestHeader('Content-Type','application/xml');
r.send('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" '+
'xmlns:ns="http://somebigcorporation.com/api/ws1/">'+
'<soapenv:Body>'+
//snip: irrelevant to the question
'</soapenv:Body></soapenv:Envelope>');
if r.status<>200 then raise Exception.Create(r.statusText);
Result:=(r.responseXML as DOMDocument).documentElement.firstChild.firstChild.selectSingleNode('importantData');
end;
The webservice responds nicely with status 200 and Content-Type: text/xml; charset=iso-8859-1.
In some cases, documentElement is nil (and the above code throws an access violation). Apparently responseXML exists, but only to offer a parseError object (it says so in the docs), and parseError.reason in these cases is An invalid character was found in text content..
Why is the parser not taking the 'charset' value from the response header? Is there a way to tell the XMLHTTP instance to use the charset value from the response header?
Update: I don't know if it's important, but the response also doesn't start with <?xml and even if it did I have no way to request/modify it so it would have an encoding="iso-8859-1" attribute.
I think you need to set the charset in the request so the result is correct.
r.setRequestHeader('Content-Type', 'application/xml; charset=ISO-8859-1');

Resources