Roby Sottini
Roby Sottini

Reputation: 2265

How to compress HTTP response?

I have a HTTP response request that is too big and slow (1.2 mb, 15 seconds, plain text). I want to compress using gzip but the server is not mine. Then I use the data for a chart

For example. I need this response to be compress:

https://rickandmortyapi.com/api/location/20

Is it possible?

I use this code that works great:

$.post("http://serverNotMine", function() {}, "text")
    .done(function(data) {
        // my code for a chart.js
    })
    .fail(function() {
        alert("Error");
    });

How can I know if the server accepts gzip?

Upvotes: 3

Views: 8920

Answers (1)

Alex Huszagh
Alex Huszagh

Reputation: 14644

The Accept-Encoding HTTP header primarily exists for this purpose, so you can specify a target encoding and the server will respond with the desired encoding among a list of choices. However, the server can choose to ignore this request, unless identity is explicitly prohibited, in which case the server can respond with a 406 error.

However, luckily for you, the server you're attempting to contact does, in fact, support the Accept-Encoding header with gzip.

>>> import requests
>>> response = requests.get('https://rickandmortyapi.com/api/location/20', 
headers={'Accept-Encoding': 'gzip'})
>>> response.headers['content-encoding']
'gzip'

Just use your HTTP client of choice with the above header. However, it is possible using the default configurations your client was already using a compression algorithm.

Upvotes: 1

Related Questions