How to send only JSON data in HTTP Header response in php? - json

i get request from android and IOS clients. I store the request in an array.
then i encode it to JSON. Now i want to sent only the JSON data in my HTTP header. How to do that? Currently its sending the html page in response i want to send only json encoded data in 200 OK header.
Below is my code:
public function index()
{
$request = array(
'request' => $this->input->get('request'),
'device_id' => $this->input->get('device_id'),
'launch_date'=> $this->input->get('launch_date'),
'allowed_hours'=>$this->input->get('allowed_hours'),
'site_id'=> $this->input->get('site_id'),
'product'=>$this->input->get('product'),
'software_version'=> $this->input->get('software_version'),
'platform_os'=> $this->input->get('platform_os'),
'platform'=> $this->input->get('platform'),
'platform_model'=> $this->input->get('platform_model')
);
$response = array(
'response_code' =>200 ,
'device_id'=> $this->input->get('device_id'),
'allowed_hours'=> $this->input->get('allowed_hours'),
'product'=>'mlc',
'prov_ur'=>NULL
);
return $this->output
->set_content_type('Content-Type: application/json')
->set_output(json_encode($response));
}
}
MY response:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: request
Filename: admin/license.php
Line Number: 22
A PHP Error was encountered
Severity: Notice
Message: Undefined index: allowed_hours
Filename: admin/license.php
Line Number: 25
A PHP Error was encountered
Severity: Notice
Message: Undefined index: allowed_hours
Filename: admin/license.php
Line Number: 40
{"response_code":200,"device_id":"70D0D01FBAD2","allowed_hours":null,"product":"mlc","prov_ur":null}array(10) { ["Host"]=> string(14) "192.168.50.123" ["Connection"]=>
string(10) "keep-alive" ["Cache-Control"]=> string(9) "max-age=0" ["Accept"]=> string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8" ["Upgrade-Insecure-Requests"]=> string(1) "1" ["User-Agent"]=>
string(110) "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
["Accept-Encoding"]=> string(19) "gzip, deflate, sdch"
["Accept-Language"]=> string(14) "en-US,en;q=0.8" ["Cookie"]=>
string(518) "cisession=OhhBBhVodwwf7Tb55AVsU32ClMS5cgmxBl15WHA%2BrGnvo1kiK%2B67BWeAuJVSV2MY25zZd0riHC9cyx9fiigiBuqkPMT%2FKE9d6et%2FXaE3F7I59P9%2FEzy5byQ5nEkJq5xwXoH1I7%2B7v62cQL21%2Bjfnk3AwIy4luM7N51IUuTqg7TxunoZFD1gJO84r8degY1imNpmDk2W%2FjsQPn9bQpkWJ9KVMxxViFDaELEU0rIfYmif%2BdvXjK9W%2Fj7iWQxZYE9ZGazgBTKlLO%2BJZHNdPrdmGPFTzTUROZdffpF%2Bb25bRMPEJsZ9CE2mdVuSn%2FEu678utd0lcd9bh%2BDbTDikrHP4jBFOLbZfWKT%2F9r5GkMBrLBl%2BlvPx9RbAq%2FIsjeA1V7c6JYf41TO1bG2XKT14QFHm8m0qY8HCal%2B%2BR8tZe9i3zy24%3Dcfc459942e4ef82a5554257216a19d621f446a25" ["If-Modified-Since"]=> string(29) "Thu, 01 Jan 1970 00:00:00 GMT" }

this is not a header problem your array do not have "allowed_hours"
Message: Undefined index: allowed_hours
you can change your code like this
$allowed_hours = "";
if(!empty($this->input->get('allowed_hours'))){
$allowed_hours = $this->input->get('allowed_hours');
}
$response = array(
'response_code' =>200 ,
'device_id'=> $this->input->get('device_id'),
'allowed_hours'=> $allowed_hours,
'product'=>'mlc',
'prov_ur'=>NULL
);

Related

Keep getting HTTP code 422, not sure whats wrong with the json payload

I am making a python module that interacts with Carousell using the requests module. Now I am trying to send a post request with a JSON payload, but I keep getting HTTP error code 422(UNPROCESSABLE ENTITY). I don't know what's wrong with my JSON payload, python dict(before it's converted to JSON) or perhaps I am missing something in my request headers.
I tried taking the raw json string(from the POST request that I captured using Chrome dev tools) converting it dict and copy that dict(printed out) and try to use it in the program. It didn't work.
login_session = requests.session()
login_session.headers.update({"DNT":"1", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36", "Origin":"https://sg.carousell.com"})
login_payload = {'requests': {'g0': {'resource': 'sso', 'operation': 'create', 'params': {'loginToken': cookies["login-token"]}, 'body': {}}}, 'context': {'_csrf': cookies["_csrf"]}}
login_cookies = {"__cfduid": cookies["__cfduid"], "_csrf": cookies["_csrf"], "gtkprId": cookies["gtkprId"], "login-token": cookies["login-token"], "redirect":"redirect"}
login_headers = {'accept':'*/*','accept-encoding':'gzip, deflate, br','accept-language':'en-GB,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,en-US;q=0.6', 'x-requested-with': 'XMLHttpRequest', 'content-type': 'application/json'}
login_data = login_session.post(query_url, cookies=login_cookies, data=json.dumps(login_payload), headers=login_header)
Heres the output from debugging logger
DEBUG:urllib3.connectionpool:https://sg.carousell.com:443 "POST /ui/iso?_csrf=TNZTMZpBdQYgRFFouCF4ELVB HTTP/1.1" 422 0
Edit:
Heres the JSON payload which was sent to the server. I am trying to replicate it.
{"requests":{"g0":{"resource":"sso","operation":"create","params":{"loginToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1NTg1MDQyMjQsImlzcyI6ImxvZ2luLmNhcm91c2VsbC5jb20iLCJzc29pZCI6IkRacG1rd1l1SXAxdDF5U3A2M1RXWExPUTJnWmRFRzBOSHd3d0ZGSm9PSkFvVFFOdGFyNWt0MDMzNm5EVHRudHoiLCJ1c2VyaWQiOiIxNDczMjI3NCJ9.x7YxdLLk1ID6_jWy4trtLzbrPnZZ0eI7g_cQN1BilF8"},"body":{}}},"context":{"_csrf":"hPPhgajp-1GMLSbgjZBNBD7z2EGPVGCuA_mU"}}
Note that login token and _csrf are data from the cookies.

Angular won't post data to API

I got a problem which I dont understand.
I try to post data to my API in a form using the following code
formSubmit() {
const req =this.http.post('http://[ip]/api/login', {
id: '7',
username: 'PostTest',
password: 'studp123lan',
matrikelnr: 'winf303666',
email: 'winf303666#example.de',
email_verified: '1'
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log("Error occured");
}
When I inspect it in the Chrome Developter tools, this is what I get:
Failed to load http://[ip]/api/login: Response for preflight has
invalid HTTP status code 404
register.component.ts:42 Error occured
And this is what I get in the network tab:
General:
Request URL:http://[ip]/api/login
Request Method:OPTIONS
Status Code:404 Not Found
Remote Address:[ip]:80
Referrer Policy:no-referrer-when-downgrade
Response Header:
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Content-Length:0
Date:Thu, 21 Dec 2017 09:00:35 GMT
Server:Kestrel
X-Powered-By:ASP.NET
Request Header:
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:[ip]
Origin:http://localhost:4200
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36
Somehow, this doesn't work. But when I Post the same data via Postman Post Request to the same URL, it works like a charm.
Can anyone explain and help?
Thanks.
404 is a page not found error : this means your endpoint isn't available at this address.
Sure, you make a postman call and it works : but did you create your postman call by hand, or used the interceptor to make it ? (The interceptor is a Chomr plugin that allows you to register all calls made by Chrome, into postman).
There must be something you have forgotten. Could you post your postman call, and if you can, try with the interceptor ?

POST error when sending JSON data in Grinder

The requirement is to make a POST request to a particular URL with a given JSON payload. The URL will only respond if the payload is correct and the request is via POST.
This is my code:
request1 = HTTPRequest()
control = HTTPPluginControl.getConnectionDefaults()
httpUtilities = HTTPPluginControl.getHTTPUtilities()
control.setProxyServer("proxy.example.com", 1234)
payload = JSONObject({
"uaaURL": "https://com-example.something.com",
"sampleID": "admin",
"sampleSecret": "password",
"sampleID2": "example-sample-el",
"sampleSecret2": "ssenjsoemal/+11=",
"username": "test",
"someAttributes": {
"Groups": [
"example_com-abc"
],
"attribute": [
"value1"
]
}
})
payload = str(payload)
url = "https://example-something.com:6443/getvalues"
headers = [
NVPair('Content-Type', 'application/json'),
NVPair('Charset', 'UTF-8'),]
class TestRunner:
def __call__(self):
result = request1.POST(url, payload, headers)
print payload, headers
Now the issue with this is that my POST request gives me a 403 forbidden. However, when I use the same payload and send the request using DHC, it gives me a 200. So I'm sure of the payload and the link I'm connecting to. The proxy also I've tested in another script and works fine. Besides, if the proxy didn't work, I wouldn't get a 403 either.
Lastly, I'm parsing it as a string because POST requires the second argument to be string that it will internally convert into byte[].
I'm really not able to understand what's happening so any insight would be immensely helpful. Thanks in advance
EDIT: Fiddler's catch of DHC's Request
POST https://example-something.com:6443/getvalues HTTP/1.1
Host: example-something.com:6444
Connection: keep-alive
Content-Length: 688
Origin: chrome-extension://aejoelaoggembcahagimdiliamlcdmfm
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
{
"uaaURL": "https://com-example.something.com",
"sampleID": "admin",
"sampleSecret": "password",
"sampleID2": "example-sample-el",
"sampleSecret2": "ssenjsoemal/+11=",
"username": "test",
"someAttributes": {
"Groups": [
"example_com-abc"
],
"attribute": [
"value1"
]
}
}
I even edited my Grinder request headers to so
headers = (
NVPair('Content-Type', 'application/json'),
NVPair('Charset','UTF-8'),
NVPair('Accept', '*/*'),
NVPair('Accept-Encoding', 'gzip, deflate, br'),
NVPair('Accept-Language', 'en-US,en;q=0.8'),
NVPair('Connection', 'keep-alive'),
)
Best guess? You are likely missing a header with some credential information to pass a proxy/firewall/access gate to the application. Your REST Client, DHC, likely is passing this additional data but grinder is not. Grab a proxy (Fiddler, Charles, etc...) and check out the handshake from DHC to your destination and then match that with Grinder. My guess is you will find the delta.
The issue was that Grinder was not able to access the port. It had nothing to do with the JSON. The URL, which runs on port 6443 was the problem and Grinder couldn't access that (don't know why). I changed my URL itself to run on the default port 8080 and instantly my script worked. Thanks for the help!

Browser cache: Json response

i tried to cache a json response from an api request using the Etag.
I'm calling something like this http://localhost:3000/api/config and getting:
Response Headers:
Cache-Control:public, max-age=31557600
Connection:keep-alive
Content-Length:11
Content-Type:application/json; charset=utf-8
Date:Wed, 13 May 2015 11:41:52 GMT
ETag:"94d52736bcd99b1ac771f13b1bbdf622"
X-Powered-By:Express
Resonse: {id: 1}
I expected the browser to cache the response and to send the Etag with the next request triggert by "f5". But this isn't the case.
Request Headers 2nd request:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:3000
Pragma:no-cache
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
So is it impossible to cache pure json response, getting by a direct api requests? Or do i miss something.
The api is an node js test implemantation done with express:
router.get('/config', function(req, res) {
var eTag = crypto.createHash('md5').update(JSON.stringify(config)).digest('hex');
res.setHeader('ETag', '"' + eTag + '"');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'public, max-age=31557600');
});
Testet with chrom(42.x) and firefox(37.x)
Thx for response.
Hi this code seems to work for me:
router.get('/config', function(req, res) {
var eTag = crypto.createHash('md5').update(JSON.stringify(config)).digest('hex');
if (req.headers['if-none-match'] && req.headers['if-none-match'] === '"' + eTag + '"') {
res.status(304);
res.end();
} else {
res.setHeader('ETag', '"' + eTag + '"');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'public, max-age=31557600');
res.send(JSON.stringify(config));
}
});
Calling the api using browser url bar http://localhost:3000/api/config
Looks like you might be using chrome.
Chrome should include the following header in the request after "f5":
If-None-Match:"94d52736bcd99b1ac771f13b1bbdf622"
If you don't see this, check the chrome settings / General and make sure that "Disable cache (while DevTools is open) is not checked:
Using jQuery we can use the ifModified option:
$.ajax({
type: "GET",
ifModified: true,
url: "http://localhost:3000/api/config"
}).then(function(data) {
. . .
});

Error in Fullcalendar with json and web2py

I´m calling:
events: {
url: '/CondominioVip/evento/evento_json.json',
error: function() {
alert('there was an error while fetching events!');
}
}
I've also tried to add type: 'POST but it didn't work either.
My controller:
def evento_json():
events= "[{'title':'event1','start':'2010-01-01'},{'title':'event3','start':'2010-01-09 12:30:00','allDay':False}]"
return events
Test call from browser (http://localhost:8000/CondominioVip/evento/evento_json.json):
[{'title':'event1','start':'2010-01-01'},{'title':'event3','start':'2010-01-09 12:30:00','allDay':False}]
Request from web2py ajax function:
Accept:application/json, text/javascript, /; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:31
Content-Type:application/x-www-form-urlencoded
Cookie:session_id_admin=127.0.0.1-f9db7d99-4e7e-4bae-a229-d6614e9599f0; cvip_language=pt-BR; session_id_condominiovip=127.0.0.1-b820cbe3-9a55-40bb-8618-8d3f9a43f7c2
Host:localhost:8000
Origin:http://localhost:8000
Referer:http://localhost:8000/CondominioVip/evento/index/2
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5
X-Requested-With:XMLHttpRequest
Response headers:
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Length:105
Content-Type:application/json
Date:Tue, 29 May 2012 02:54:04 GMT
Expires:Tue, 29 May 2012 02:54:03 GMT
Pragma:no-cache
Server:Rocket 1.2.4 Python/2.7.3
Set-Cookie:cvip_language=pt-BR; expires=Wed, 30-May-2012 02:54:04 GMT; Path=/, session_id_condominiovip=127.0.0.1-b820cbe3-9a55-40bb-8618-8d3f9a43f7c2; Path=/
X-Powered-By:web2py
Response:
[{'title':'event1','start':'2010-01-01'},{'title':'event3','start':'2010-01-09 12:30:00','allDay':False}]
I'm out of options. Any help would be apprecianted.
Update:
I've installed the JsonView extension on Chrome, so returning a string is not considered a json response.
I made some changes:
def evento_json():
rows = db(evento.id>0).select(evento.id,evento.titulo,evento.data_hora_inicio,evento.data_hora_fim)
events = []
for row in rows:
event = {'title': row['titulo'],
'start': row['data_hora_inicio'],
'end': row['data_hora_fim'],
'allDay': False,
'url': URL(c='evento', f='index', args=[row['id']], extension=False)}
events.append(event)
return events
But web2py throws an error. I´ve printed "events" and "json(events)" before send it to generic.json, and the format is exactly what fullcalendar expects.
The way I found to stop the error is:
In controller:
def evento_json():
import datetime
start = datetime.datetime.fromtimestamp(int(request.vars['start'])).strftime('%Y-%m-%d %H:%M:%S')
end = datetime.datetime.fromtimestamp(int(request.vars['end'])).strftime('%Y-%m-%d %H:%M:%S')
set = db((evento.id>0) &
(evento.data_hora_inicio >= start) &
(evento.data_hora_fim <= end))
if (not auth.has_membership(auth.id_group(role='site_admin'), auth.user.id)) and \
(not auth.has_membership(auth.id_group(role='cond_admin'), auth.user.id)):
set = set(evento.flag_disp==True)
rows = set.select(evento.id,
evento.titulo,
evento.data_hora_inicio,
evento.data_hora_fim,
evento.flag_disp)
events = []
for row in rows:
event = {'title': row['titulo'],
'start': row['data_hora_inicio'],
'end': row['data_hora_fim'],
'allDay': False,
'url': URL(c='evento', f='index', args=[row['id']], extension=False),
'color': 'blue' if row['flag_disp'] is True else 'red'}
events.append(event)
if events:
from gluon.serializers import json
return XML(json(events))
else:
return '{}'
And create a view evento/evento_json.json with the following:
{{=response._vars)}}
It works! But seems a bug to me. I'm not sure if I'm doing something wrong.
Maybe try:
events= "[{'title':'event1','start':'2010-01-01'},{'title':'event3','start':'2010-01-09T12:30:00Z','allDay':false}]"
(Changed the event3 start date/time to ISO8601 format as per the API, and changed "False" to "false".)