I'm trying to get latitude and longitude from cell tower info using Google's geolocation api.
It requires a valid JSON with information like MCC, MNC, cellId, lac etc.., My PHP post request looks like this.
<?php
header("Access-Control-Allow-Origin: *");
$mcc = $_POST["mcc"];
$mnc = $_POST["mnc"];
$cellId = $_POST["cellId"];
$lac = $_POST["lac"];
$post_array = array(
"cellId" => (int) $cellId,
"locationAreaCode" => (int) $lac,
"mobileCountryCode" => (int) $mcc,
"mobileNetworkCode" => (int) $mnc,
);
$post_data = json_encode(array('cellTowers' => array($post_array)));
echo $post_data;
$url = "https://www.googleapis.com/geolocation/v1/geolocate?key=".$api_key; // not including api key here but its there in my code
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => $post_data
));
$result = curl_exec($ch);
echo "Result: ".$result;
curl_close($ch);
?>
However I get an error saying bad request in the response. The error is shown below.
Result: {
"error": {
"errors": [
{
"domain": "geolocation",
"reason": "invalidRequest",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
I thought my JSON was not in the correct format but it was working with the following command line execution, so that can't be the issue.
$ curl -d #your_filename.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY"
The above command in terminal gives lattitude and longitude properly with the same JSON in a file. What am I doing wrong ?
Try this
$DadosLBS['homeMobileCountryCode'] = $data['MCC'];
$DadosLBS['homeMobileNetworkCode'] = $data['MNC'];
$DadosLBS['radioType'] = 'gsm';
$DadosLBS['carrier'] = $data['MNCOperator'];
$DadosLBS['cellTowers'] = [
[
'mobileCountryCode' => $data['MCC'],
'mobileNetworkCode' => $data['MNC'],
'age' => $data['Age'],
'timingAdvance' => $data['TA'],
'locationAreaCode' => $data['LAC'],
'cellId' => $data['CELL_ID'],
'signalStrength' => $data['SIGNAL'],
],
];
//Ver detalhes da API no https://developers.google.com/maps/documentation/geolocation/intro?hl=pt-br
$service_url = "https://www.googleapis.com/geolocation/v1/geolocate";
//Chave de acesso
$Curl_Data = array(
'key' => <YOUR KEY HERE>
);
$CurlQueryString = http_build_query($Curl_Data);
//Preparando o método a ser enviado os dados
$Metodo = array(
CURLOPT_URL => $service_url.'?'.$CurlQueryString // Define URL to be called
);
//Criando s string de dados
$DadosPost = json_encode($DadosLBS);
//Preparando as opções padrões do CUrl
$Curl_Adicional_Options = array(
CURLOPT_CUSTOMREQUEST => "POST"
,CURLOPT_POSTFIELDS => $DadosPost
,CURLOPT_RETURNTRANSFER => true // return web page
,CURLOPT_CONNECTTIMEOUT => 15 // time-out on connect
,CURLOPT_TIMEOUT => 15 // time-out on response
,CURLOPT_FAILONERROR => true //
,CURLOPT_HEADER => false // don't return headers
,CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($DadosPost)
) // Dados para o cabeçalho do post
,CURLOPT_FOLLOWLOCATION => true // follow redirects
,CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
,CURLOPT_SSL_VERIFYPEER => false
,CURLOPT_SSL_VERIFYHOST => false
);
$Curl_Options = array_replace_recursive($Metodo,$Curl_Adicional_Options);
$cURLConn = curl_init();
curl_setopt_array($cURLConn, $Curl_Options);
$vDados['Curl']['Output'] = curl_exec($cURLConn);
$vDados['Curl']['Error'] = curl_error($cURLConn);
$vDados['Curl']['ErrorNum'] = curl_errno($cURLConn);
$vDados['Curl']['ErrorMsg'] = curl_strerror($vDados['Curl']['ErrorNum']);
$vDados['Curl']['Info'] = curl_getinfo($cURLConn);
curl_close($cURLConn);
if ($vDados['Curl']['ErrorNum'] != 0) {
$Dados['loc'] = array(
'status' => 'ERROR',
'error' => array(
'error_cod' => $vDados['Curl']['ErrorNum'],
'error_msg' => $vDados['Curl']['ErrorMsg']
)
);
return $Dados['loc'];
}
//Tratando as respostas
$vDados['Curl']['Dados'] = json_decode($vDados['Curl']['Output']) or die("Error: Cannot create object");
print_r($vDados['Curl']['Dados']);
Don't forget to create our key on google console.
Related
I have a question ..
My app gives me the following information:
HTTP + JSON
The following are sample HTTP requests and responses. The placeholders shown need to be replaced with actual values.
POST /json/reply/Zona
HTTP/1.1
Host: equatepro.azurewebsites.net
Content-Type: application/json
Content-Length: length
{"zonaId":0,"nombre":"String","creadoPor":"String","creadoFecha":"/Date(-62135596800000-0000)/","modificadoPor":"String","modificadoFecha":"/Date(-62135596800000-0000)/","estado":"String","nota":"String","borrar":false}
AND then
The following routes are available for this service:
POST /api/zonas
PUT /api/zonas/{zonaId}
enter image description here
enter image description here
I'm trying to communicate with my webservice using PUT method
My code
<?php
$pantalla="zonas";
%id =8;
$url= "http: //miapp.com /api/zonas/8".$pantalla ;
$url = $url ."/" . $id;
// complete url http://miapp.com/api/zonas/8
//build json
$ConstructorJson = array(
'ZonaId' => $Datos['txt_codigo'],
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
$json = json_encode($ConstructorJson);
$opts = array(
"http" => array(
"method" => "PUT",
"header" => "Accept: application/xml\r\n",
"content" => $json
)
);
$context = stream_context_create($opts);
$response = file_put_contents($url,'8',false,$context);
?>
Give me the following error
Warning: file_put_contents(http: //miapp .com/api/zonas/8): failed to open >stream: HTTP wrapper does not support writeable connections in C:\xampp\htdocs\Codigo2.0\models\zonas.model.php on line 34
and nothing happens.
I would rather connect using PHP curl.
$ConstructorJson = array(
'ZonaId' => $Datos['txt_codigo'],
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
$json = json_encode($ConstructorJson);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http: //miapp.com/api/zonas/8/zonas",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Accept: application/xml\r\n",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
HTTP wrapper does not support writeable connections - basically, PHP is telling you "Hey, you can't use this function to write to a file that lives on the internet. How do you expect me to write a file # http: //miapp .com/api/zonas/8? Not gonna happen".
I assume what you're trying to do is to send a PUT request # that location to update a zonas resource with ID 8.
Solution
Consider using a proper HTTP client that can send actual HTTP request methods and conform to the HTTP spec.
My personal favourite inside PHP is Guzzle -
http://docs.guzzlephp.org/en/stable/. Guzzle is a standalone package and can be downloaded from their site. You can use it in any PHP project - without or without a framework.
With Guzzle, you'd do something like the following:
$client = new GuzzleHttp\Client();
$json = json_encode($ConstructorJson);
$headers = [
"Accept" => "application/xml\r\n"
]
$request = new Request('PUT', $url, ['body' => $json, 'headers' => $headers]);
$client->send($request);
I finally solved the problem (thank you Kyle O'Brien)
Code
<?php
// web service url + tabla + id
$url = "mywebservice.com/zonas/8";
$Datos = $_POST;
//create a array with dates
$ConstructorJson = array(
'Nombre' => $Datos['txt_Nombre'],
'CreadoPor' => $Datos['txt_CreadoPor'],
'CreadoFecha' => $Datos['txt_CreadoFecha'],
'ModificadoPor' => $Datos['txt_ModificadoPor'],
'ModificadoFecha' => $Datos['txt_ModificadoFecha'],
'Estado' => $Datos['cbo_Estado'],
'Nota' => $Datos['txt_Notas']
);
//convert array to json
$json = json_encode($ConstructorJson);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
Someone could help me ? I'm trying to do a request by the code bellow, but anything happen, any message appears. I believe my code it's right:
public function subscribe(){
$json_url = 'https://apisandbox.cieloecommerce.cielo.com.br/1/sales/';
$json_string = json_encode(array(
"MerchantOrderId"=>"2014113245231706",
"Customer" => array(
"Name" => "Comprador rec programada"
),
"Payment" => array(
"Type" => "CreditCard",
"Amount" => 1500,
"Installments" => 1,
"SoftDescriptor" => "Assinatura Fraldas"
)
));
$ch = curl_init($json_url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch); // Getting jSON result string
print_r($result);
}
Find link with instructions of the site:
you will reiceive this:
[
{
"Code": 114,
"Message": "The provided MerchantId is not in correct format"
}
]
with this code:
function subscribe(){
$json_url = 'https://apisandbox.cieloecommerce.cielo.com.br/1/sales/';
$json_string = json_encode(
array(
"MerchantOrderId"=>"2014113245231706",
"Customer" => array(
"Name" => "Comprador rec programada"
),
"Payment" => array(
"Type" => "CreditCard",
"Amount" => 1500,
"Installments" => 1,
"SoftDescriptor" => "Assinatura Fraldas"
)
)
);
$headers = array(
'Content-Type: application/json',
'MerchantId: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx',
'MerchantKey: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx',
'RequestId: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx'
);
$ch = curl_init($json_url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options ); $result = curl_exec($ch);
print_r($result);
}
subscribe()
It would be interesting what HTTP status code you get:
print_r(curl_getinfo($ch, CURLINFO_HTTP_CODE));
I humbly come before the people for some much needed assistance with this..
I am using (or trying to use) the skyscanner API - http://partners.api.skyscanner.net/apiservices/pricing/v1.0 as documented here. But I am coming up against this error:
HTTP request failed! HTTP/1.1 411 Length Required
PHP attempt 1
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers);
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
My server doesn't support cURL so I'm in need of a solution without it. I'm using localhost with WAMP but I have also tried a live version which comes up with the same error and seemingly same problem. I have tried almost every combination of variables in order to correct the error with a discouraging amount of success (none). This is one such variation including the form contents that I am attempting to send.
PHP attempt 2
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$params = array( 'country' => 'GB',
'currency' => 'GBP',
'locale' => 'en-GB',
'originplace' => 'LHR',
'destinationplace' => 'EDI',
'outbounddate' => '2016-10-10',
'adults' => '1'
);
$query = http_build_query($params);
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers,
'content' => $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
This throws out:
Content-type not specified
Followed by:
HTTP/1.1 400 Bad Request
If you can help I would appreciate some insight right about now.
Many thanks!
You create headers in a wrong way - instead of an array, headers should be passed as a string.
$headers = "Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/xml\r\n";
You can use below snippet to create the correct request:
function prepare_headers($headers) {
return
implode('', array_map(function($key, $value) {
return "$key: $value\r\n";
}, array_keys($headers), array_values($headers))
);
}
function http_post($url, $data, $ignore_errors = false) {
$data_query = http_build_query($data);
$data_len = strlen($data_query);
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml',
'Content-Length' => $data_len
);
$response =
file_get_contents($url, false, stream_context_create(
array('http' => array(
'method' => 'POST',
'header' => prepare_headers($headers),
'content' => $data_query,
'ignore_errors' => $ignore_errors
)
)
));
return (false === $response) ? false :
array(
'headers' => $http_response_header,
'body' => $response
);
}
Example usage of http_post method:
$result = http_post('http://business.skyscanner.net/apiservices/pricing/v1.0', array(
'apiKey' => 'YOUR_API_KEY',
'country' => 'UK',
'currency' => 'GBP',
'locale' => 'en-GB',
'locationSchema' => 'iata',
'originplace' => 'EDI',
'destinationplace' => 'LHR',
'outbounddate' => '2016-10-10',
'adults' => '1'
), false);
Parameter $ignore_errors in http_post method is reponsible for fetching the content even on failure status codes (400, 500, etc.). If you receive Bad request, set ignore_errors = true -> you'll receive full response from server.
I'm using the LinkedIn REST API to post updates to a users timeline.
Since a few days I get an Internal server error response from LinkedIn but the code worked before.
PHP:
$postTitle = "hello";
$postDesc = "world ";
$submitted-url = "http://example.com";
$submitted-image-url = "http://images.example.com/img/hello.jpg";
$comment = "foobar";
$postData = array('visibility' => array('code' => 'connections-only'),
'content' => array('title' => $postTitle,'description' => $postDesc,'submitted-url' => $postURL,'submitted-image-url' => $postImage), 'comment' => $postComment);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='.$oauthToken.'&format=json'
);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
How to fix that error?
Your code is invalid PHP (perhaps because of some edits you made before posting?); modifying it to:
$postTitle = "hello";
$postDesc = "world ";
$postURL = "http://example.com";
$postImage = "http://images.example.com/img/hello.jpg";
$postComment = "foobar";
$oauthToken = "<token>";
$postData = array(
'visibility' => array('code' => 'connections-only'),
'content' => array(
'title' => $postTitle,
'description' => $postDesc,
'submitted-url' => $postURL,
'submitted-image-url' => $postImage
),
'comment' => $postComment
);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?oauth2_access_token='.$oauthToken.'&format=json');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json"),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
works if only $oauthToken is set to a valid token. Assuming your real code is correct the only possiblity left is that your OAuth token has expired and you need to obtain a new one first. By adding CURLOPT_VERBOSE => TRUE to the cURL options you would find out more about the error that LinkedIn returns.
You may considering using the LinkedIn PHP SDK (provided by the community) instead: https://github.com/Happyr/LinkedIn-API-client
We faced similar issue with Linkedin API recently. Finally figured out the fix by changing the url.
New URL : "https://api.linkedin.com/v1/people/~/shares"
Instead of specifying 'oauth2_access_token' in the query string,
add it in the header - specify :
"Authorization", "Bearer " + accessToken.
And finally in the request body parameter, add your json/xml data to post
You have to Use your Authentication Token in Request Headers.
This is the working code. Try it.
$postTitle = "hello";
$postDesc = "world ";
$submitted-url = "http://example.com";
$submitted-image-url = "http://images.example.com/img/hello.jpg";
$comment = "foobar";
$oauthToken = "TokenHere";
$postData = array('visibility' => array('code' => 'connections-only'),
'content' => array('title' => $postTitle,'description' => $postDesc,'submitted-url' => $postURL,'submitted-image-url' => $postImage), 'comment' => $postComment);
$ch = curl_init('https://api.linkedin.com/v1/people/~/shares?format=json');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('x-li-format: json', "Content-Type: application/json", "Bearer: ".$oauthToken.""),
CURLOPT_POSTFIELDS => json_encode($postData)
));
$response = curl_exec($ch);
I am using the following code to update an issue in JIRA but unable to diagnose the error. The error I am getting is as follows:
HTTP Status 415 - Unsupported Media Type
type Status report
message Unsupported Media Type
The code I have written is as follows:
$resource_array['api_name'] = 'issue/SPC-60';
$resource_array['fields'] = array (
'summary' => 'CLONE - Testing label stuff',
'assignee' =>
array (
'emailAddress' => 'avinashk.dubey#gmail.com',
),
'customfield_10649' =>
array (
'id' => '10668',
),
'customfield_10616' => 'This is observation'
);
$data = putJiraAPI($resource_array);
print_r($data);
////////////////////////////////////////////
function putJiraAPI($resource_array)
{
$api_name = $resource_array['api_name'];
unset($resource_array['api_name']);
$result = put_to($api_name, $resource_array);
if(is_array($result))
{
return $result;
}
else
{
return "error while getting data using ".BASE_URL.API_URL.$resource_string;
}
}
function put_to($api_name, $resource_array)
{
$jdata = json_encode($resource_array);
print_r($jdata);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_URL => BASE_URL . API_URL . $api_name,
CURLOPT_USERPWD => USER_NAME . ':' . PASSWORD,
CURLOPT_POSTFIELDS => $jdata,
CURLOPT_HTTPHECURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_RETURNTRANSFER => true
));
echo BASE_URL . API_URL . $api_name;
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result,true);
}
Actually, I did wrong here:
CURLOPT_HTTPHECURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
it should be:
CURLOPT_HTTPHEADER => array('Content-type: application/json'),