I've reduced to the simplest form, and am still stumbling...I've spent more than 30 hours researching and testing. According to all of the posts which never show more than 15° of the entire circle, this is supposed to be really easy.
I want to:
Send query parameters (in JSON) from an Android Phone to a WAMP server...This may be as much as a complete dump of a local SQLite table, so query strings just won't cut it.
Have the WAMP server read the JSON data, formulate a SQL query and submit to the mySQL database
Package a response as JSON data (from a simple "OK" to a full table dump)
Return the response package to the Android phone
This is already a fully functional WAMP application, and I want to integrate Android access. For this reason, I really want to avoid AJAX, since I want to maintain consistency with what's already in place.
I've reduced this to the simplest loop and am hitting snags. I'm using send.php to post some JSON data to receive.php. At this point, I just need receive.php to read the data and send it back (slightly modified) to send.php
send.php is properly reading stock JSON sent from receive.php. I just can't get any sign of life that receive.php even recognizes the JSON sent to it.
PLEASE don't direct me towards cURL...from everything I've found regarding Android and JSON, cURL is a tangent which will send me full circle back into nonfunctionality.
APACHE 2.2.22, PHP 5.4.3
Like I said, I've reduced this to the simplest form to demonstrate a full circle...
send.php:
<?php
$url = "http://192.168.0.102:808/networks/json/receive.php";
$data = array(
'param1' => '12345',
'param2' => 'fghij'
);
$json_data = json_encode($data);
$options = array(
'http' => array(
'method' => 'POST',
'content' => $json_data,
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n" .
'Content-Length: ' . strlen($json_data) . "\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result , true);
echo '[' . $response['param1'] . "]\n<br>";
//THIS WORKS! send.php displays "Initialized"
?>
receive.php
<?php
$newparam = 'Initialized';
//HERE I NEED TO read the JSON data and do something
$data = array(
'param1' => $newparam,
'param2' => 'pqrst'
);
header('Content-type: application/json');
echo json_encode($data);
?>
It is actually easy, as stated in all the incomplete explanations...I got the full circle to work finally
I've chosen simplicity to prove I could travel full circle, and I have now done so.
send.php
<?php
//The URL of the page that will:
// 1. Receive the incoming data
// 2. Decode the data and do something with it
// 3. Package the results into JSON
// 4. Return the JSON to the originator
$url = "http://192.168.0.102:808/networks/json/receive.php";
//The JSON data to send to the page (above)
$data = array(
'param1' => 'abcde',
'param2' => 'fghij'
);
$json_data = json_encode($data);
//Prep the request to send to the web site
$options = array(
'http' => array(
'method' => 'POST',
'content' => $json_data,
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
//Make the request and grab the results
$result = file_get_contents( $url, false, $context );
//Decode the results
$response = json_decode( $result , true);
//Do something with the results
echo '[' . $response['param1'] . "]\n<br>";
?>
receive.php
<?php
//K.I.S.S. - Retrieve the incoming JSON data, decode it and send one value
//back to send.php
//Grab the incoming JSON data (want error correction)
//THIS IS THE PART I WAS MISSING
$data_from_send_php = file_get_contents('php://input');
//Decode the JSON data
$json_data = json_decode($data_from_send_php, true);
//CAN DO: read querystrings (can be used for user auth, specifying the
//requestor's intents, etc)
//Retrieve a nugget from the JSON so it can be sent back to send.php
$newparam = $json_data["param2"];
//Prep the JSON to send back
$data = array(
'param1' => $newparam,
'param2' => 'pqrst'
);
//Tell send.php what kind of data it is receiving
header('Content-type: application/json');
//Give send.php the JSON data
echo json_encode($data);
?>
AND Android integration...called with a Button.onClickListener
public void getServerData() throws JSONException, ClientProtocolException, IOException {
//Not critical, but part of my need...Preferences store the pieces to manage JSON
//connections
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String netURL = prefs.getString("NetworkURL", "");
// "http://192.168.0.102:808/networks/json"
String dataPage = prefs.getString("DataPage", "");
// "/receive.php"
//NEEDED - the URL to send to/receive from...
String theURL = new String(netURL + dataPage);
//Create JSON data to send to the server
JSONObject json = new JSONObject();
json.put("param1",Settings.System.getString(getContentResolver(),Settings.System.ANDROID_ID));
json.put("param2","Android Data");
//Prepare to commnucate with the server
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(theURL);
//Attach the JSON Data
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
//Send and Receive
String response = httpClient.execute(postMethod,resonseHandler);
//Begin reading and working with the returned data
JSONObject obj = new JSONObject(response);
TextView tv_param1 = (TextView) findViewById(R.id.tv_json_1);
tv_param1.setText(obj.getString("param1"));
TextView tv_param2 = (TextView) findViewById(R.id.tv_json_2);
tv_param2.setText(obj.getString("param2"));
}
Related
I am working on a Slack slash command in PHP that takes a Twitter username and returns that person's latest tweet.
I can't figure out how to display the user's profile image to make it look as nice as Slack's Twitter integration.
The issue it seems to me is that I have to include 'unfurl_media: true' in JSON that gets sent back to Slack. That means I can't just use echo to print out the Twitter data I want, which is in an associative array.
I tried grabbing the Twitter data I want from the associative array, encoding it again in JSON and then printing that. But all that does is print the JSON as plain text. I checked a JSON validator and it says what gets printed to Slack is valid JSON, so I don't understand why slack isn't converting it to a styled message.
Any suggestions?
Here's the code. It's frankencode pulled from a bunch of different places that I am trying to bend to my will.
<?php
require_once('TwitterAPIExchange.php');
$command = $_POST['command'];
$text = $_POST['text'];
$token = $_POST['token'];
if($token != '[insert your Slack slash command token here]'){
$msg = ":squirrel: The token for the slash command doesn't match. We're done here until IT fixes it. Don't worry, Squirrelock is on the case.";
die($msg);
echo $msg;
}
$settings = array(
'oauth_access_token' => "[insert access token here]",
'oauth_access_token_secret' => "[insert access token secret here]",
'consumer_key' => "[insert consumer key here]",
'consumer_secret' => "[insert consumer secret here]"
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name='.$text.'&count=1';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), $assoc = TRUE);
foreach($string as $items)
{
$reply = "".$items['user']['profile_image_url']." *".$items['user'] ['name']."* ".$items['user']['screen_name']. "\n ".$items['text']."\n ".$items['created_at']."";
}
$data = json_encode(array(
"response_type" => "in_channel",
"text" => $reply,
"unfurl_media" => true,
"unfurl_links" => true
));
echo $data;
?>
Moving my comment down to an answer, since it seems to have fixed the problem:
Add header('Content-Type: application/json'); before echo $data;. The issue is that Slack is interpreting your response as text. It will interpret it as JSON only if the Content-Type is correct.
Need to request some code two times in my app. Fist request url as ajax call, and also need to request this url in controller (something like hmvc). I know how to develop this via curl but I found another kind of idea how to implement this, just use function file_get_contents with before prepared params. This my code:
// Setup limit per page
$args['offset'] = $offset;
$args['limit'] = $this->_perpage;
// --
// Convert search arguments to the uri format
$data = http_build_query($args);
// Define request params
$options = array(
'http' => array(
'header' => 'Content-type: application/json' . PHP_EOL .
'Content-Length: ' . strlen($data) . PHP_EOL,
'method' => 'POST',
'content' => $data,
),
);
$context = stream_context_create($options);
$result = file_get_contents(
'http://'.$_SERVER['HTTP_HOST'].'/search/items', FALSE, $context
);
Request method was detected ok in requested uri, but params wasn't passed. Why this is not pass arguments to request? Where is bug in my code? Many thanks for any answers.
http_build_query builds application/x-www-form-urlencoded content. (not application/json)
There is a full example:
How to post data in PHP using file_get_contents?
Content type should be application/x-www-form-urlencoded. If you want to stay with application/json, try to get posted data using file_get_contents("php://input").
Not sure if anyone can help me out with a question.
I had to write some php for the company I work for that lets us integrate with an API that accepts a JSON body. I used the cUrl method, and the script is working great.
If I wanted to build another php page that would accept the request im sending, how would I go about this?
Say I wanted to allow someone to send this same request to me, and then wanted the info they sent to go into my database, how would turn their request into php strings?
Here is the code im sending.
<?
$json_string = json_encode(array("FirstName" => $name, "MiddleName" => " ", "LastName" => $last));;
// echo $json_string;
// jSON URL which should be requested
$json_url = 'http://www.exampleurl.com';
// jSON String for request
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Accept: application/json;charset=utf-8',
'Content-Type: application/json;charset=utf-8',
'Expect: 100-continue',
'Connection: Keep-Alive') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
echo $result;
$myArray = json_decode($result);
$action = $myArray->Action;
?>
To get the raw data from the POST that you would be receiving you would use $postData = file_get_contents('php://input');
http://php.net/manual/en/reserved.variables.post.php
Then you would json_decode() the contents of that POST back into JSON.
http://php.net/manual/en/function.json-decode.php
Not really good understood your question. May be you are looking for the way to read raw POST data? In that case open and read from php://stdin stream.
$stdin = fopen('php://stdin', 'r');
By the way read here ( http://php.net/manual/en/function.curl-setopt.php ) how to use CURLOPT_POSTFIELDS. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value.
I've been trying to get the pastebin API to instead of telling me the pastebin link , just output the raw data. The PHP code is this :
<?php
$api_dev_key = 'Stackoverflow(fake key)';
$api_paste_code = 'API.'; // your paste text
$api_paste_private = '1'; // 0=public 1=unlisted 2=private
$api_paste_expire_date = 'N';
$api_paste_format = 'php';
$api_paste_code = urlencode($api_paste_code);
$url = 'http://pastebin.com/api/api_post.php';
$ch = curl_init($url);
?>
Normally this would upload the $api_paste_code into pastebin , showing up like pastebin.com/St4ck0v3RFL0W , but instead I want it to generate the raw data.
The raw data link is http://pastebin.com/raw.php?i= , can anyone help?
Reference : http://pastebin.com/api
As far as I see, the response contains the Pastebin URL generated when the content is created. An Url like this:
http://pastebin.com/UIFdu235s
So what you only need is to get rid of "http://pastebin.com/" doing:
$id = str_replace("http://pastebin.com/", "", $url_received_on_last_step);
And then, append it to the raw url you provided:
$url_raw = "http://pastebin.com/raw.php?i=".$id;
And you'll get the raw data.
First off, please note that you must send a POST request to the pastebin.com API, not GET. So don't use urlencode() on your input data!
To get the raw paste url from the page url, you have several options. But the easiest is probably:
$apiResonse = 'http://pastebin.com/ABC123';
$raw = str_replace('m/', 'm/raw.php?i=', $apiResponse);
Finally, here is a complete example:
<?php
$data = 'Hello World!';
$apiKey = 'xxxxxxx'; // get it from pastebin.com
$apiHost = 'http://pastebin.com/';
$postData = array(
'api_dev_key' => $apiKey, // your dev key
'api_option' => 'paste', // action to perform
'api_paste_code' => utf8_decode($data), // the paste text
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => "{$apiHost}api/api_post.php",
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($postData),
));
$result = curl_exec($ch); // on success, some string like 'http://pastebin.com/ABC123'
curl_close($ch);
if ($result) {
$pasteId = str_replace($apiHost, '', $result);
$rawLink = "{$apiHost}raw.php?i={$pasteId}";
echo "Created new paste.\r\n Paste ID:\t{$pasteId}\r\n Page Link:\t{$result}\r\n Raw Link:\t{$rawLink}\r\n";
}
Running the above code, outputs:
c:\xampp\htdocs>php pastebin.php
Created new paste.
Paste ID: Bb8Ehaa7
Page Link: http://pastebin.com/Bb8Ehaa7
Raw Link: http://pastebin.com/raw.php?i=Bb8Ehaa7
I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>