httpful
A Chainable, REST Friendly, PHP HTTP Client. A sane alternative to cURL.
Httpful: The REST Friendly PHP HTTP Client Library httpful is a simple, chainable php library intended to make speaking http painless and interacting with rest apis a breeze. it includes built-in smart parsing, clean custom header support, basic and client side cert authentication, payload serialization and more.
I've installed Httpful as described with Composer adding to composer.json the following:
{
"require": {
"nategood/httpful": "*"
}
}
I'm using Laravel 4 so i ran composer install
I've checked if the plugin is installed and is there, in fact under the vendor folder of laravel i can find it. But i keep getting the following error:
ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Httpful' not found'
I'm missing some steps?
Thank you in advance
Source: (StackOverflow)
I'm using HTTPful to send some requests in PHP and get data in JSON, but the library is converting the result into objects, where I want the result to be an array. In other words, its doing a json_decode($data)
rather than json_decode($data, true)
.
There is, somewhere, an option to use the latter, but I can't figure out where. The option was added in v0.2.2:
- FEATURE Add support for parsing JSON responses as associative arrays instead of objects
But I've been reading documentation and even the source, and I don't see the option anywhere... The only way I can think of is making my own MimeHandlerAdapter
which does a json_decode($data, true)
but it seems like a pretty backwards way of doing it if there is an option somewhere...
Source: (StackOverflow)
I'm using Jersey for a RESTful web service in Java. I'm consuming them from a PHP client. I have it working fine with JSON as follows:
PHP: (using httpful phar)
$uri="http://localhost:8080/YYYYY/rest/common/json";
$r = \Httpful\Request::post($uri)
->body({"name":"MyName"})->send();
return $r;
Java RESTful WS:
@POST
@Path(value="json")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_JSON)
public String jsonTest(final JaxData data)
{
System.out.println(data.toString());
return "this is the name: "+data.name;
}
Java binding class:
@XmlRootElement
public class JaxData {
@XmlElement public String name;
}
Now what I want to do is to send the following JSON structure:
{
"title":"MyTitle",
"names":[
{
"name":"nameOne"
},
{
"name":"nameTwo"
}
],
"city":"MyCity",
"country": "MyCountry"
}
So as you can see I want to send objects inside objects apart from the primitive types of Java. How can I do this from the Java side? Thank you!
Source: (StackOverflow)
From http://phphttpclient.com I followed "Install option 1" and the first "quick snippet".
I end up with the following, with Request undefined.
Additionally, and perhaps relatedly, I am confused by the fact that one of the code samples says "$response = Request::get" and another says "$response = \Httpful\Request::get". Is the latter valid PHP?
I have PHP 5.6.7.
What am I doing wrong?
Source: (StackOverflow)
I am using Httpful PHP library from http://phphttpclient.com/ , here is my sample code :
$data = array(
'code' => $request->query->get('code'),
'client_id' => $this->container->getParameter('GOOGLE_CLIENT_ID'),
'client_secret' => $this->container->getParameter('GOOGLE_CLIENT_SECRET'),
'redirect_uri' => $google_redirect,
'grant_type' => "authorization_code"
);
$response = Request::post($url)->body($data)->sendsType(Mime::FORM)->send();
var_dump($response);
die();
my question is how to add form data .
I tried to read the documentation but I cannot found any explanation, there are only send xml and Json example, but I cannot get normal POST with form data inside a request.
somebody please help me..
Source: (StackOverflow)
I'm trying to learn REST, and thought it might be good to start with a PHP REST client such as Httpful. I just can't seem to get it to work. I downloaded the httpful.phar file and placed it in my working directory. Then created a simple php file with the following contents from an example on the their site:
<?php
// Point to where you downloaded the phar
include('httpful.phar');
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = Request::get($uri)->send();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
?>
I've tried multiple examples on the site, but only get a blank page when I load it in my browser.
Thanks for any help you can give!
Source: (StackOverflow)
I have a little laravel app and I added the http://phphttpclient.com/ - httpful REST Client to work with an external api - http://en.help.mailstore.com/spe/Management_API_-_Using_the_API
I was able to "speak" with the mailstore api. Here is one example:
public function GetEnvironmentInfo()
{
$uri = 'https://bla.com:8474/api/invoke/GetEnvironmentInfo';
$response = Httpful::post($uri)
->authenticateWith('admin', 'password')
->send();
$errors = $response->body->error;
$version = $response->body->result->version;
$license = $response->body->result->licenseeName;
dd($version . $license . $errors);
}
That function works. But I have a problem when I try to send additional data to the api.
In the manual of the api you can find the following sentences.
"When a function needs additional data, this data must be send urlencoded. The HTTP header Content-Type: application/x-www-form-urlencoded should be set."
For example I want to set the user password with the help of the api.
SetUserPassword
Set password of MailStore user.
Arguments
Name Type Description
instanceID string Unique ID of MailStore instance in which this command is invoked.
userName string User name of MailStore user.
password string Password of MailStore user.
I tried this code.
public function SetUserPassword()
{
$uri = 'bla.com:8474/api/invoke/SetUserPassword';
$response = Httpful::post($uri)
->authenticateWith('admin', 'password')
->addHeaders(array(
'instanceID' => 'bla',
'userName' => 'myuser',
'password' => 'mypassword'
))
->sendsType(\Httpful\Mime::FORM)
->send();
dd($response->body->error);
}
And here is the error response i get:
object(stdClass)[142]
public 'message' => string 'Argument instanceID is missing.' (length=31)
public 'details' => string 'System.Exception: Argument instanceID is missing.
bei #Y3c.#VGc.#X3c(#ncb #tPc, #8xe #I9f, String #GPf, NameValueCollection #P5b, Int32 #joc)
bei #Y3c.#VGc.#Slc(#LLc #Rmc, #8xe #I9f)
' (length=192)
I added the instanceID and the other arguments to the header, but the api can't find the arguments or values.
I think the problem is the urlencode? Can you help me?
Thanks!
Source: (StackOverflow)
I am currently building a e-mail client (inbound and outbound sending) using Mandrill as the e-mail sending / inbound service and Laravel 3.x.
In order to send messages, I am using the HTTPful bundle with the Mandrill using the following code in my mail/compose POST method.
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
Link to better formatted code above: http://paste.laravel.com/m79
Now as far as I can tell from the API log, the request is correctly made (with the expected JSON) and a response of the following format is sent back:
[
{
"email": "test@test.com",
"status": "queued",
"_id": "longmessageID"
}
]
However, what I am trying to do is access the response from the request (specifically the _id attribute), which is in JSON. Now as far as I'm aware, the HTTPful class should do this automatically (using json_decode()). However, accessing:
$request->_id;
is not working and I'm not entirely sure how to get this data out (it is required so I can record this for soft-bounce, hard-bounce and rejection messages for postmaster-like functionality)
Any assistance would be appreciated.
Edit
Using the following code, results in the mail being sent but an error returned:
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
if ( $request[0]->status == "queued" ) {
$success = true;
}
Results in an exception being thrown: Cannot use object of type Httpful\Response as array
Source: (StackOverflow)
I have to code a PHP front end for my Jasper reports. I could successfully connect to the server, authenticate and view the repositories using the jasper REST calls. However, when I try to access a report, I get the following error in the response body:
Report not found (uuid not found in session)
The php code is given below:
$uri = "http://localhost:8080/jasperserver/rest/report/samples/Client_Information_Report?RUN_OUTPUT_FORMAT=html";
//PUT request to run the report
$response = Httpful\Request::put($uri, $payload)
->authenticateWith("jasperadmin", "jasperadmin")
->send();
$xml = new SimpleXMLElement($response->body);
$uuid = (String)$xml->uuid; //The uuid is successfully returned
$uri = "http://localhost:8080/jasperserver/rest/report/$uuid?file=report";
$report = Httpful\Request::get($uri)
->authenticateWith("jasperadmin", "jasperadmin")
->send();
I am able to confirm that a uuid is returned with the first PUT. Is there anything I am missing here? Any help is appreciated.
Source: (StackOverflow)
I managed to get a SOAP client working for a client but I am now trying to use REST for a slightly different project. I am using Httpful. From what I have read it is what I need in order to do what I've been asked.
This is my code so far.
/* MAIN RESTFUL */
$xml_file = './Project.xml';
$xsd_file = './Project.xsd';
$end_uri = 'https://****.com/Service.svc/CreateProject';
/* TEMP TEXTAREA FIELD */
if(!isset($_POST['submit']))
$_xml = file_get_contents($xml_file);
else
$_xml = $_POST['xml_input'];
echo '<form method="post" action=""><textarea name="xml_input" rows="10" cols="100">' . $_xml . '</textarea><br /><input type="submit" name="submit" value="Send"></form><br /><a rel='nofollow' href="./">Reset Form</a><br /><br />';
/* END TEMP TEXTAREA FIELD */
if(isset($_POST['submit']))
$xml_file = $_POST['xml_input'];
if(isset($_POST['submit']))
{
$xsd_validate = new DOMDocument();
$xsd_validate->loadXML($xml_file);
if($xsd_validate->schemaValidate($xsd_file))
$sendXML = true;
if($sendXML == true)
{
require('./httpful-master/bootstrap.php');
$request = \Httpful\Request::post($end_uri)
->body($xml_file)
->sendsXml()
->send();
if($request)
echo 'SENT!';
}
}
The guy I am working with doesn't really know a lot about REST either but apparently there is a way to retrieve a response from the request being sent. Does anyone know, or at least can point me in the right direction, to solve this?
Thanks.
EDIT: Sorry, just to elaborate. The XML is placed into the textarea field then validated against an XSD file. If this is successful it will then post that XML to the REST endpoint.
Source: (StackOverflow)
I'm new to using composer packages. I've gotten a few to work, but I came across a Google Maps package I'd like to use and I can't get it to load properly.
php-google-maps package
My attempt at using the package:
<?php
require './vendor/autoload.php';
use \PHPGoogleMaps\Service\Geocoder;
use \PHPGoogleMaps\Service\GeocodeError;
use \PHPGoogleMaps\Service\GeocodeResult;
use \PHPGoogleMaps\Service\GeocodeException;
$map = new \PHPGoogleMaps\Map;
// Rest of GMap code goes here...
?>
This fails with the message Class 'PHPGoogleMaps\Map' not found
composer.json File:
{
"require" : {
"nategood/httpful":"*",
"nesbot/carbon": "dev-master",
"php-google-maps/php-google-maps": "dev-master"
}
}
Source: (StackOverflow)
Basically I would like to see an example on how to download a file.
I can't seem to find on phphttpclient website any doc or example about it.
In curl, the request would look like this:
curl -o hello.txt -H "X-Auth-Token: xxxxxxxxxxxxxxxxxxx" http://site_where_to download/hello.txt
Thanks.
Source: (StackOverflow)
Playing arond with Httpful library, but I stuck with response body. Response body returned in encoded state.
print_r($response->raw_body);
returns something like that:
��Y]��F}ﯘ�l�e33��H��K�K?P�>!͗w]'�ND ...
Alternatively I trying to post the same request with cURL. As expected, cURL returned regular response with http header and readable xml data.
Krumo-printed Httpful response object. Body isn't empty (string, 1210 chars), but looks like it does.
Source: (StackOverflow)
I am building a service in lumen to support my laravel application and I've run into a strange problem. When I call the service using httpful, lumen doesn't receive the headers, they're null. However when it sends the response back the laravel the function that called the service has those values filled. This is preventing me from using the header values that was sent with the request in the service function. Has anyone experienced this before?
My service controller:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
class FileController extends Controller
{
public function index(Request $request)
{
// these are both null
$filename = $request->header("filename");
$fileLocation = $request->header("fileLocation");
return response()->json([
'filename' => $filename,
'path' => $fileLocation
});
}
}
Here is my laravel controller
private function callFileService()
{
// Configure the Service location
$servername = filter_input(
INPUT_SERVER,
'SERVER_NAME',
FILTER_SANITIZE_STRING);
$uri = 'http://' . $servername . '/FileService/public/file';
$response = Httpful\Request::get($uri)
->addHeaders(array(
"filename"=>'file',
"fileLocation"=>'location',
))
->expectsJson()
->send();
dd($response);
return $response;
}
The following is returned from the $response array:
+body: {#192 ▼
+"filename": "file"
+"path": "location"
}
The response array also contains the request object and it does show the headers being attached to the request. Here is the whole Response object.
Response {#190 ▼
+body: {#192 ▶}
+raw_body: "{"filename":"file","path":"location"}"
+headers: Headers {#191 ▶}
+raw_headers: """
HTTP/1.0 200 OK␍
Date: Tue, 09 Jun 2015 13:31:38 GMT␍
Server: Apache/2.4.9 (Win64) PHP/5.5.12␍
X-Powered-By: PHP/5.5.12␍
Cache-Control: no-cache␍
Content-Length: 37␍
Connection: close␍
Content-Type: application/json"""
+request: Request {#189 ▼
+uri: "http://localhost/FileService/public/file"
+method: "GET"
+headers: array:3 [▼
"filename" => "file"
"fileLocation" => "location"
"Content-Length" => 0
]
+raw_headers: """
GET /FileService/public/file HTTP/1.1␍
Host: localhost␍
Expect:␍
User-Agent: Httpful/0.2.19 (cURL/7.36.0 PHP/5.5.12 (WINNT) Apache/2.4.9 (Win64) .5.12 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36)␍
Content-Type: ␍
Accept: */*; q=0.5, text/plain; q=0.8, text/html;level=3;q=0.9, application/json␍
filename: file␍
fileLocation: location␍
Content-Length: 0␍
"""
+strict_ssl: false
+content_type: null
+expected_type: "application/json"
+additional_curl_opts: []
+auto_parse: true
+serialize_payload_method: 2
+username: null
+password: null
+serialized_payload: null
+payload: null
+parse_callback: null
+error_callback: null
+send_callback: null
+follow_redirects: false
+max_redirects: 25
+payload_serializers: []
+_ch: :Unknown {@228}
+_debug: null
}
+code: 200
+content_type: "application/json"
+parent_type: "application/json"
+charset: "utf-8"
+meta_data: array:26 [▶]
+is_mime_vendor_specific: false
+is_mime_personal: false
-parsers: null
}
Source: (StackOverflow)
I use httpful to send http request and get the response to display in request.php
include('httpful.phar');
$response = \Httpful\Request::get('http://domain/response.php')->send();
echo '<textarea rows="20" cols="100">';
echo $response;
echo '</textarea>';
In response.php, I use header to redirect the request to another page, but I cannot get the expected response.
header("HTTP/1.1 301 Moved Permanently");
header("Location:http://otherdomain/other_response.php");
echo 'internal response page'
I have also tried
header("HTTP/1.1 302 Found");
but it still only get the response 'internal response page'
what is the correct way to redirect/forward the request to other_response.php?
Source: (StackOverflow)