HTTP Content Type returned by server when a response is not required - http-headers

When returning html to the client, I set the server content type to:
"text/html"
When I returning JSON to the client, I set the server content type to:
"application/json"
I have a special case where the client makes an AJAX call to do something unimportant and the client really doesn’t benefit by getting a reply from the server so I just return an empty reply and set the server content type to:
"application/json"
Is this OK even though my reply is empty?
Thank you

Related

Is it correct to return 200 Ok HTTP status for a POST request?

Usually, we use POST to create a resource on the server-side.
So ideally if everything goes right, the server should respond either with a 201 Created HTTP status or in case of an asynchronous operation with 202 Accepted HTTP status.
Is there any valid scenario where a POST request can be returning a 200 OK HTTP status?
Or should we never use 200 OK HTTP status for a POST request?
I see 200 as a very common response to POST requests on internet. It's fine to use it.
From RFC 7231:
6.3.1. 200 OK
The 200 (OK) status code indicates that the request has succeeded.
The payload sent in a 200 response depends on the request method.
For the methods defined by this specification, the intended meaning
of the payload can be summarized as:
GET a representation of the target resource;
HEAD the same representation as GET, but without the
representation
data;
POST a representation of the status of, or results obtained from,
the action;
PUT, DELETE a representation of the status of the action;
OPTIONS a representation of the communications options;
TRACE a representation of the request message as received by the
end
server.
And section 4.3.3:
Responses to POST requests are only cacheable when they include
explicit freshness information (see Section 4.2.1 of [RFC7234]).
However, POST caching is not widely implemented. For cases where an
origin server wishes the client to be able to cache the result of a
POST in a way that can be reused by a later GET, the origin server MAY
send a 200 (OK) response containing the result and a Content-Location
header field that has the same value as the POST's effective request
URI (Section 3.1.4.2).
Yes, You can return 200 Ok HTTP status, but you SHOULD return a response BODY.
In general, we have 3 options according to your API requirements:
Return 201 Created HTTP status, with EMPTY BODY.
In case you don't need to return a response body.
Return 200 Ok HTTP status, with BODY.
In case you need to return a response body [containg created resource].
Return 202 Accepted HTTP status, with EMPTY BODY.
In case the action will be queued.

Fiddler POST Invalid Header Name

I am sending a POST request to a WCF Web service using fiddler, and the service responds with HTTP 400: The request has an invalid header name.
The post request looks like this:
User-Agent: Fiddler
Host: localhost:49392
Content-Type: application/json
Content-Length: 0
{ "clientFirstName" : "John"}
My endpoint is defined as follows:
[OperationContract]
[System.ServiceModel.Web.WebInvoke
(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json,
BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped,
UriTemplate = "MakeReservation")]
String MakeReservation(Stream reservationStream);
MORE
First of all, the JSON was in the wrong pane. I moved it to the Request Body pane.
I changed the prototype of the function to take a String instead of Stream as the input parameter. The service now accepts my call and returns 200, but in the debugger I see that the input parameter String is null. When I change it back to Stream, I get 400 again.
YET MORE
Enable tracing gives me at trace file with the following message:
Incoming message for operation 'MakeReservation' (contract 'ITalLimoService' with namespace
'http://tempuri.org/') contains an unrecognized http body format value 'Json'. The expected body
format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the
binding. See the documentation of WebContentTypeMapper for more details.
As noted int the WebInvoke definitiuon, both the RequestFormat and ResponseFormat are set to WebMessageFormate.Json. Why is IIS complaining about this?
I don't know why this works, but for some reason removing the following line from the fiddler Composer did the trick:
Content-Type: application/json
And that is that. I would give points for an explanation.
I know this post is old. But very strange, when I removed the header "application/json" it worked.
Has it got to do with server setup?
The request could not be understood by the server due to deformed syntax. The client SHOULD NOT repeat the request without modifications.If request to your server with data that is in the correct format, but its bad data. eg: a Posted String value to an API endpoint that expected a String value; but, the value of the string contained data that was something else.
The syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains syntactically correct but semantically wrong XML instructions.

How to set response headers with Rikulo Stream server?

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.

Reading response from proxy using WinHttpQueryHeader()

How to find out if the response is sent from the proxy or end-server by using WinHttpQueryHeader() function? I have tried using WINHTTP_QUERY_PROXY_AUTHENTICATE as the dwInfoLevel paramter to the function winHttpQueryHeader() but the buffer I got is NULL.
int bufferSize = 0;
char lpOutBuffer[500];
ReturnVal = WinHttpQueryHeader(Handle, WINHTTP_QUERY_PROXY_AUTHENTICATE, NULL, &bufferSize);
ReturnVal= WinHttpQueryHeader(Handle, WINHTTP_QUERY_PROXY_AUTHENTICATE, lpOutBuffer, &bufferSize);
lpOutBuffer is NULL.
Actually what I think the problem here is that I get the bufferSize 0 in the first WinHttpQueryHeader and so the second WinHttpQueryHeader does not fill the lpOutBuffer (since bufferSize is 0). Why is the bufferSize returned as 0?
Contrary to this, if I use the InfoLevel as WINHTTP_QUERY_RAW_HEADERS_CRLF, I do get the correct output and bufferSize is not 0, it gets filled after the first WinHttpQueryHeader() call..
If a HTTP server requires authentication the HTTP response code is 401 and the corresponding response header is WWW-Authenticate. If a proxy server requires authentication the HTTP response code is 407 and the corresponding response header is Proxy-Authenticate. I suggest checking the response for the proper HTTP code and then retrieving the corresponding header.
As for the WINHTTP_QUERY_PROXY_AUTHENTICATE query flag, the documentation states:
Retrieves the header that is used to identify the user to a proxy that
requires authentication. This header can only be retrieved before the
request is sent to the server.
So that particular flag has nothing to do with a response from the server. It is a request header that is sent to identify the user to the proxy.

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