This commit is contained in:
thefosk
2014-01-08 18:14:42 -08:00
parent 7b388b04a7
commit bd4975cb3c
3 changed files with 46 additions and 1 deletions

View File

@@ -113,6 +113,25 @@
return Unirest::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password); return Unirest::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password);
} }
/**
* This function is useful for serializing multidimensional arrays, and avoid getting
* the "Array to string conversion" notice
*/
private static function http_build_query_for_curl( $arrays, &$new = array(), $prefix = null ) {
if ( is_object( $arrays ) ) {
$arrays = get_object_vars( $arrays );
}
foreach ( $arrays AS $key => $value ) {
$k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key;
if ( is_array( $value ) OR is_object( $value ) ) {
Unirest::http_build_query_for_curl( $value, $new, $k );
} else {
$new[$k] = $value;
}
}
}
/** /**
* Send a cURL request * Send a cURL request
* @param string $httpMethod HTTP method to use (based off \Unirest\HttpMethod constants) * @param string $httpMethod HTTP method to use (based off \Unirest\HttpMethod constants)
@@ -141,7 +160,8 @@
$ch = curl_init(); $ch = curl_init();
if ($httpMethod != HttpMethod::GET) { if ($httpMethod != HttpMethod::GET) {
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $body); Unirest::http_build_query_for_curl($body, $postBody);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postBody);
} else if (is_array($body)) { } else if (is_array($body)) {
if (strpos($url,'?') !== false) { if (strpos($url,'?') !== false) {
$url .= "&"; $url .= "&";

View File

@@ -31,6 +31,30 @@ class UnirestTest extends UnitTestCase
$this->assertEqual("thefosk", $form->nick); $this->assertEqual("thefosk", $form->nick);
} }
public function testUpload() {
$response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ),
array(
"file" => "@" . dirname(__FILE__) . "/test_upload.txt"
)
);
$this->assertEqual(200, $response->code);
$files = $response->body->files;
$this->assertEqual("This is a test", $files->file);
}
public function testPostMultidimensionalArray()
{
$response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ),
array('key'=>'value','items'=>array('item1','item2')));
$this->assertEqual(200, $response->code);
$form = $response->body->form;
$this->assertEqual("item1", $form->{"items[0]"});
$this->assertEqual("item2", $form->{"items[1]"});
}
public function testPut() public function testPut()
{ {
$response = Unirest::put("http://httpbin.org/put", array( "Accept" => "application/json" ), $response = Unirest::put("http://httpbin.org/put", array( "Accept" => "application/json" ),

View File

@@ -0,0 +1 @@
This is a test