How to set response headers with Rikulo Stream server? - http-headers

I have one API that returns information in JSON, and for that, I would indicate that the content-type of the HttpResponse is application/json.
So, with Rikulo, I have something like :
connect.response.headers.set(HttpHeaders.CONTENT_TYPE, contentTypes['json']);
But when I request my API, it told me that the headers are immutable.
HttpException: HTTP headers are not mutable
#0 _HttpHeaders._checkMutable (http_headers.dart:267:21)
#1 _HttpHeaders.set (http_headers.dart:31:18)
Therefore, how can I set my response headers, or there is a native solution with Rikulo to return JSON data ?

You can set the contentType property directly:
connect.response.headers.contentType = contentTypes["json"];
If you'd like to set the header instead, you have to pass a String object (which Dart SDK expects):
connect.response.headers.set(HttpHeaders.CONTENT_TYPE,
contentTypes['json'].toString());
But the error message shall not be as you posted. Like Kai suggested in the comment, the message indicates you have output some data before setting the header.

Related

RAML, specify API request Content-Length value

I'm trying to set the value of the Content-Length property to 0 in my RAML file.
I first stumbled upon this thread : How to specify API request header value in RAML
When I tried implementing it with this code :
/update:
post:
description: Store updated data in database
headers:
Content-Length:
enum: [0]
body:
...
I got the response 400 Bad Request :
{
"code": "REQUEST_VALIDATION_ERROR",
"message": "Required header Content-Length is missing."
}
My IDE told me a string was expected but feeding with ["0"] didn't solve the problem.
(I'm testing my API specification in Mulesoft Design Center.)
So is there something I did wrong or is there another way to set the Content-Length to 0 in the request's header ?
You should only try to define custom headers in RAML. A required header of the HTTP protocol like Content-Length must not be defined. It should be automatically generated to prevent errors.

How to set http response code in Parse Server cloud function?

A parse server cloud function is defined via
Parse.Cloud.define("hello", function(request, response) {..});
on the response, I can call response.success(X) and response.error(Y), and that sets the http response code and the body of the response.
But how do I define a different code, like created (201)?
And how do I set the headers of the response?
thanks, Tim
You are allowed to return any valid JSON from response.success(). Therefore, you could create an object with fields such as code, message, and value, so you can set the code, give it a string descriptor, and pass back the value you normally would, if there is one. This seems to accomplish what you need, though you will have to keep track of those codes across your platforms. I recommend looking up standard http response codes and make sure you don't overlap with any standards.

ShopStyle API - How to Invoke an HTTP request

How do I Invoke an HTTP request with a particular URL and process the body of the response as XML?
Information Provided by ShopStyle:
HOW TO USE THE API:
Choose the method that returns the data your application needs. For example, the /products method is used to get products that match a given category or brand.Construct a URL for that method with the appropriate host, method name, and query parameters. Invoke the URL as an HTTP GET.
When the HTTP response arrives, extract the required data elements from the response's body.The rest of this document describes the details of constructing the right URL for each of the API methods. The XML format of the responses may be seen by clicking on the sample URLs shown for each method. The responses in JSON format contain identical information, just in a different format.
SHOPSTYLE API URLS
All ShopStyle API URLs have the following form:
http://api.shopstyle.com/api/VERSION/METHOD_NAMEpid=YOUR_API_KEY&format=FORMAT&...
The METHOD_NAME is taken from the list of methods in the various API shown at left (Press Link To View List of Methods-https://www.shopstylecollective.com/api/overview).
COMMON API PARAMETERS
All methods in the API accept these parameters:
API_KEY (my unique key is ******************)
pid Unique API_KEY string that is assigned to the caller. You can find your API Key on the Account Settings page.
FORMAT
The format of the response. Supported values are:
json - The response is in JSON format with UTF-8 encoding. This is the default if the parameter is absent.
xml - The response is in XML format with UTF-8 encoding.
jsonp - The response is in JSON format with UTF-8 encoding wrapped in a JavaScript method called padding. The padding must be specified with the query parameter 'callback'. Only single expressions (function reference, or object property function reference) are accepted as valid padding.
When set to 1 or 'true' the HTTP status will always be 200. Use the field "errorCode" in the response to detect whether the API Call was successful. By default, when an error occur the HTTP Status of the response will be different than 200
Again I am a beginner, so please provide detailed information on how to retrieve CATEGORY data (Examples: Dresses, Tops, Buttoms, etc) in XML format.**
Thank you!!!
Here's a simple example to get your started. Copy the code below and put it into a file, say "cat.php". Then run it by typing "php cat.php" at a command prompt (assumes you have php on your machine):
<?php
// don't show dom parse errors
libxml_use_internal_errors(true);
// grab the xml from the api
$response = file_get_contents("http://api.shopstyle.com/api/v2/categories?pid=TEST&format=xml");
$doc = new DOMDocument();
$doc->loadHTML($response);
// grab all the categories
$elements = $doc->getElementsByTagName('categories');
foreach($elements as $node){
foreach($node->childNodes as $child) {
// get the name out of the category
$nodes = $child->getElementsByTagName("name");
foreach ($nodes as $name) {
echo $name->nodeValue . PHP_EOL;
}
}
}

Add http header in HTTPFound() with pyramid

I have a Pyramid application where I have the following line of code:
return HTTPFound(location=request.route_url('feeds'))
However I want to pass an extra parameter in the headers. Im trying with this:
headers = {"MyVariable": "MyValue"}
return HTTPFound(location=request.route_url('feeds'),headers=headers)
However the view_config of "feeds" does not get MyVariable in the headers. I'm checking it with the following code:
print "**************"
for key in request.headers.keys():
print key
print "**************"
What am I doing wrong?
headers is meant to be a sequence of (key, value) pairs:
headers = [("MyVariable", "MyValue")]
This lets you specify a header more than once. Also see the Response documentation, the headers keyword is passed on as headerlist to the Response object produced. Also see the HTTP Exceptions documentation:
headers:
a list of (k,v) header pairs
However, headers are only sent to the client; they are not passed on by the client to the next request that they are instructed to make. Use GET query parameters if you need to pass information along to the redirection target, or set values in cookies or in the session instead.
To add on query parameters, specify a _query directory for route_url():
params = {"MyVariable": "MyValue"}
return HTTPFound(location=request.route_url('feeds', _query=params))
and look for those query parameters in request.GET:
for key in request.GET:
print key, request.GET.getall(key)
Due to the way HTTP works, what you are asking is not possible. You can use either GET parameters to pass the data, or you can store the data in a cookie instead.

Upload file to Solr with HttpClient and MultipartEntity

httpclient, httpmime 4.1.3
I am trying to upload a file through http to a remote server with no success.
Here's my code:
HttpPost method;
method = new HttpPost(solrUrl + "/extract");
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
MultipartEntity me = new MultipartEntity();
me.addPart("myfile", new InputStreamBody(doubleInput, contentType, fileId));
method.setEntity(me);
//method.setHeader("Content-Type", "multipart/form-data");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse hr = httpClient.execute(method);
The server is Solr.
This is to replace a working bash script that calls curl like this,
curl http://localhost:8080/solr/update/extract?literal.id=bububu&commit=true -F myfile=#bububu.doc
If I try to set "Content-Type" "multipart/form-data", the receiving part says that there's no boundary (which is true):
HTTP Status 500 - the request was rejected because no multipart boundary was found
If I omit this header setting, the server issues an error description that, as far as I discovered, indicates that the content type was not multipart [2]:
HTTP Status 400. The request sent by the client was syntactically incorrect ([doc=null] missing required field: id).
This is related to [1] but I couldn't determine the answer from it. I was wondering,
I am in the same situation but didn't understand what to do. I was hoping that the MultipartEntity would tell the HttpPost object that it is multipart, form data and have some boundary, and I wouldnt set content type by myself. I didn't quite get how to provide boundaries to the entities - the MultipartEntity doesn't have a method like setBoundary. Or, how to get that randomly generated boundary to specify it in addHeader by myself - no getBoundary methor either...
[1] Problem with setting header "Content-Type" in uploading file with HttpClient4
[2] http://lucene.472066.n3.nabble.com/Updating-the-index-with-a-csv-file-td490013.html
I am suspicious of
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
In the first line, is fileId a string or file pointer (or something else)? I hope it is a string. As for the second line, you can rather set a normal parameter.
I am trying to tackle the HTTP Status 400. I dont know much Java (or is that .Net?)
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error