Giter Site home page Giter Site logo

yii2-httpclient's Introduction

HTTP Client Extension for Yii 2


This extension provides the HTTP client for the Yii framework 2.0.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-httpclient

or add

"yiisoft/yii2-httpclient": "~2.0.0"

to the require section of your composer.json.

yii2-httpclient's People

Contributors

acorncom avatar alexkart avatar arhell avatar avinasx avatar bizley avatar bscheshirwork avatar cebe avatar egorrishe avatar germanow avatar henryvolkmer avatar igorgolovanov avatar klimov-paul avatar kwazaro avatar lacek avatar lav45 avatar machour avatar maoxuner avatar mikehaertl avatar ofixone avatar rahimov avatar rhertogh avatar rickykurt avatar samdark avatar silverfire avatar slamdunk avatar softark avatar vuongxuongminh avatar wirwolf avatar zhangdi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-httpclient's Issues

Cannot Install via Composer

We cannot install with this command
composer require --prefer-dist yiisoft/yii2-httpclient "*"

But we can
composer require --prefer-dist yiisoft/yii2-httpclient "dev-master"

Please change documentation or release a version :(

Provide ability to get full request URL

There should be ability to get full request URL for the case it is composed using Request::url and Client::baseUrl.
Currently actual URL is composed at Request::prepareUrl().

PHP 5.4 / StreamTransport / header problem

What steps will reproduce the problem?

Using 2.0.1 of this extension, I ran into trouble with StreamTransport and a system I'm working with. Make a POST call to a website which then sets a cookie on login (using the HTTP client) and then attempt to work with the cookie ($response->cookies). If running into this issue, the headers being sent to Client#createResponse in StreamTransport#send will include additional readbuf information that breaks header parsing.

What's expected?

the $responseHeaders variable sent to Client#createResponse will just be a simple array without additional stream transport information:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: Apache-Coyote/1.1
    [2] => X-XSS-Protection: 0
    [3] => Set-Cookie: SESSIONID=<changed-to-protect-the-innocent>; Path=/; Secure; HttpOnly
    [4] => Content-Type: text/html;charset=ISO-8859-1
    [5] => Date: Wed, 10 Aug 2016 21:34:26 GMT
    [6] => Connection: close
)

This will then lead to $response->cookies being useable as expected.

What do you get instead?

the $responseHeaders variable sent to Client#createResponse includes additional stream transport information:

Array
(
    [headers] => Array
        (
            [0] => HTTP/1.1 100 Continue
            [1] => HTTP/1.1 200 OK
            [2] => Server: Apache-Coyote/1.1
            [3] => X-XSS-Protection: 0
            [4] => Set-Cookie: SESSIONID=<changed-to-protect-the-innocent>; Path=/; Secure; HttpOnly
            [5] => Content-Type: text/html;charset=ISO-8859-1
            [6] => Content-Length: 312
            [7] => Date: Wed, 10 Aug 2016 21:34:17 GMT
        )

    [readbuf] => Resource id #84
)

Additional info

Works fine on PHP 5.5.9 / Ubuntu 14.04. Not sure if this is a PHP 5.4 issue or an issue specific to the PHP build of Gentoo with my host. Happy to send in a patch if we find we want it ...

Q A
Yii version 2.0.9
PHP version PHP 5.4.44--pl0-gentoo
Operating system Linux / Gentoo custom build / EngineYard

composer install error

error message : The requested package yiisoft/yii2-httpclient could not be found in any version, there may be a typo in the package name.

I'm used yii2-app-advanced

composer.json
use
"minimum-stability": "stable"

Ошибка установки через composer

Если следовать документации, и прописать:

"yiisoft/yii2-httpclient": "~2.0.0"

с:

"minimum-stability": "stable",

получаем ошибку, что нет стабильной версии.
Следовательно инструкция написана неправильно.

CURLINFO, Url, LastUrl

Было бы хорошо иметь возможность к доступу данных CURLINFO, Например к
CURLINFO_EFFECTIVE_URL

В результирующих данных, полезно иметь запрашиваемый Url в качестве одного из атрибутов.
При редиректе хорошо получать и конечный Url.

HTTP Request Failed when in url have `&amp;`

I have small code like this:

function checkUser($username)
{
     $client = new Client(['baseUrl' => 'http://dev.mysite.com/api/queryinfo']);
     $hasilJson = new Json();
     $numberValidSubs = 0;

     $response = $client->get('user_info',['_key' => 'mykey', 'login' => $username])->send();

     if ($response->isOk) {
          // do something check here
     } else {
          return false;
     }
}

But, I get this error:

fopen(http://dev.mysite.com/api/queryinfo/user_info?_key=mykey&amp;login=agungsijawir): failed to open stream: HTTP request failed!

I notice that there is &amp; in generated URL. How can I remove &amp; in generated URL?

Thank you.

Option followLocation not working

I think the option followLocation is not working, here is how i try to use it:

        $httpclient = new Client(['baseUrl' => 'http://localhost']);

        $response = $httpclient->createRequest()
            ->setUrl('login.php')
            ->setData(['login' => 'user', 'passwd' => 'xyz'])
            ->setMethod('post')
            ->setOptions([
                          'followLocation'  => true,
                          //'maxRedirects'    => 2,
                      ])
            ->send();

On success, login.php give a new Location url in header but $response does not follow it.

`Request` lost `batchSend`

I want to use curl_multi but request without batchSend call.
Failed to find any guidance.
How to do this?

Fix phpdoc comments to be more IDE friendly

In yii\httpclient\Request majority of methods return $this for method chaining and their phpdoc says @return $this self reference. This is not IDE friendly and PHPStorm for example can't type hint chaining, it actually says that can't find methods in class '$this'.

Consider doc example

$response = $client->createRequest()
    ->setMethod('post')
    ->setUrl('http://domain.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => '[email protected]'])
    ->send();

Everything after setMethod is not working (type hinting) in PHPStorm.
Consider changing the phpdoc to @return self or @return Request for normal type hinting.

Events?

Will you raise proper events in the extension?
I find myself in a situation where i'd use a beforeSend and afterSend event rather than extending the client class to take some action based on the returned content.

Exceptions name collision

Hello,
Today I catch error: "Fatal error: Cannot use yii\base\Exception as Exception because the name is already in use in /path/to/project/vendor/yiisoft/yii2-httpclient/Response.php on line 10"

In last version (2.0.0.1) was added class yii\httpclient\Exception, but in same namespace "yii\httpclient" in class Response.php me have next code: "use yii\base\Exception;". And now in Response.php we have two classes with same name: "Exception".

UrlEncodeFormatter charset support

when i use this urlencodeformatter for chinese language,i can't change the charset to utf-8;
so i need to change the code, line 50 to this " $request->getHeaders()->set('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');"

Executing POST request instead of GET

I'm using this extension to talk with Gitlab REST API and faced issue that GET requests are not performing right in some cases.

class Gitlab extends \yii\httpclient\Client
{
    public $privateToken;
    public $projectId;

    public function createRequest()
    {
        $request = parent::createRequest();
        $request->setFormat(self::FORMAT_JSON);
        $request->addHeaders([
            'PRIVATE-TOKEN' => $this->privateToken,
        ]);
        return $request;
    }
}

$response = $gitlab->get("projects/{$gitlab->projectId}/repository/branches/{$prefix}{$issue}")->send();
if ($response->statusCode == 200) {
    // Do something
}

httpclient logs that GET request execution is being performed but in fact, a POST request is performed. Debugging led me to CurlTransport:123:

switch ($method) {
    case 'GET':
        break;
    case 'POST':
        $curlOptions[CURLOPT_POST] = true;
        break;
    default:
        $curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
}

When I deleted case 'GET' part, I got an expected result.

Any thoughts about this? Is it neccessary to NOT set CURLOPT_CUSTOMREQUEST option in case of GET and POST? Maybe we can set it always to desired method?

advanced instance setup

I use the yii2-httpclient to load data from an REST-service for building the webpages.
Mostly 2-3 request are needed to select all necessary informations.
So I have an Rest-Model-Class where I create an client instance in the constructor area to use this instance for multiple requests.
$client = new Client([ 'baseUrl' => 'http://my.domain', 'transport' => 'yii\httpclient\CurlTransport']);
But: the REST service is only available by using an proxy and is protected by an HTTP Basic Auth mechanism. This means, i have to set the proxy setting and Header-Tag for basic Auth for every single request.

$client->createRequest()
        ->addHeaders(['Authorization' => 'Basic qST47....='])
        ->setOptions([
            'proxy' => 'myproxy.domain:8080', 
            'timeout' => 5, 
        ]);

Is there a way to put those configuration settings at "new Client" level, not on "createRequest" level?
If not: what is your recommendation to set this parameter only once?

Creating the request in the constructor once an modifying the reqest (setUrl, setData, setMethod) every time it's needed?

Additional info

*happy, that this extension exists

Q A
Yii version 2.0.9
PHP version 7.0.8
Operating system Ubuntu 16.04

Getting error while trying to install using composer

Hello,

While trying to install using composer, getting following error message.

[InvalidArgumentException]
Could not find package yiisoft/yii2-httpclient at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

Could you please help me on this.

Code review

I have complete the extension.
Now it requires review from the @yiisoft/core-developers and potential users.
I suppose at least 2 members of the core team should provide thier feedbacks before release.
Feel free to open issues for the inconsistencies or other problems found.

Naming convention

I disagree with the name of the classes TransportCulr, TransportStream, ParserJson, FormatterJson, etc.
Other classes in Yii in general have the next name format - or <Type>

Example:

  • Validator, EmailValidator, StringValidator, SafeValidator, ...
  • Session, CacheSession, DbSession, ...
  • Action, ErrorAction, CaptchaAction, ...
  • Exception, ConflictHttpException, ForbiddenHttpException, ...
  • ...

I suggest to change the next classes to general name format:

  • FormatterJson => JsonFormatter
  • FormatterUrlEncoded => UrlEncodedFormatter
  • FormatterXml => XmlFormatter
  • ParserJson => JsonParser
  • ParserXml => XmlParser
  • ParserUrlEncoded => UrlEncodedParser
  • TransportCurl => CurlTransport
  • TransportStream => StreamTransport

Add CURLOPT_NOBODY for HEAD requests

HEAD requests without curl option CURLOPT_NOBODY fails with timeout error:

Exception while handling command:
Curl error: #28 - Operation timed out after 9006 milliseconds with 0 out of 60497 bytes received in /app/vendor/yiisoft/yii2-httpclient/CurlTransport.php:51
#0 /app/vendor/yiisoft/yii2-httpclient/Client.php(213): yii\httpclient\CurlTransport->send(Object(yii\httpclient\Request))
#1 /app/vendor/yiisoft/yii2-httpclient/Request.php(302): yii\httpclient\Client->send(Object(yii\httpclient\Request))

Request code:

$response = Yii::$app->httpclient->head($url)->send();

Working example:

$response = Yii::$app->httpclient->head($filename, [], [
    CURLOPT_NOBODY => true,
])->send();

PHP Notice (and Warning) on POST requests

What steps will reproduce the problem?

<?php
require __DIR__ . '/vendor/autoload.php';
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');

use yii\httpclient\Client;

$client = new Client();
$response = $client->createRequest()
    ->setMethod('post')
    ->setUrl('http://example.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => '[email protected]'])
    ->send();

What's expected?

Safe run.

What do you get instead?

Notice: Trying to get property of non-object in vendor/yiisoft/yii2/helpers/BaseStringHelper.php on line 111
Warning: mb_strlen(): Unknown encoding "" in vendor/yiisoft/yii2/helpers/BaseStringHelper.php on line 111

Additional info

This Yii method is called from /var/www/sandbox.dev/vendor/yiisoft/yii2-httpclient/Client.php:257.

Issue is reproduced only on POST requests (not on GET ones).

Q A
Yii vesion 2.0.9
PHP version 7.0.8-4
Operating system Ubuntu 16.04

Logging and profiling support

Should be provided logging and profiling for the sending HTTP requests.
Both features should be configurable, allowing to be disabled in order to save performance.

Setup Travis CI web hook

'Travis CI' web hook should be enabled for this repository, allowing automatic passing of unit tests.

Error Second Array on Data Response is NULL

What steps will reproduce the problem?

API Resfull endpoint has array on your body response, for example:

{
  "code": 412,
  "httpMessage": "Precondition Failed",
  "message": "Request Active ",
  "data": {
    "requestId": 10,
    "userId": "17",
    "registryDate": "2016-08-19 21:54:40",
    "contractedServiceData": {
      "id": 6,
      "status": true
    }
  },
  "errors": null
}

What's expected?

Expected an array on tag contractedServiceData, for example:

array (size=5)
  'code' => int 412
  'httpMessage' => string 'Precondition Failed' (length=19)
  'message' => string 'Request Active' (length=14)
  'data' => 
    array (size=9)
      'requestId' => int 10
      'userId' => string '17' (length=2)
      'registryDate' => string '2016-08-17 20:42:35' (length=19)
      'contractedServiceData' => 
         array (size=2)
           'id' => 6
           'status' => true
  'errors' => null

What do you get instead?

My current response is tag contractedServiceData null

array (size=5)
  'code' => int 412
  'httpMessage' => string 'Precondition Failed' (length=19)
  'message' => string 'Request Active' (length=14)
  'data' => 
    array (size=9)
      'requestId' => int 10
      'userId' => string '17' (length=2)
      'registryDate' => string '2016-08-17 20:42:35' (length=19)
  'contractedServiceData' => null
  'errors' => null

Additional info

This is my code to request:

      $client = new Client([
            'baseUrl' => $this->baseUrl,
        ]);
                    $response = $client->createRequest()
            ->setUrl("user_requests/$orderId")
                ->setMethod('get')
                ->addHeaders([
                    'content-type' => 'application/json',
                    'authorization' => "Bearer $tokenBearer"
                ])
            ->setFormat(Client::FORMAT_JSON)
            ->setData([])
            ->send();
Q A
Yii version 2.0.9
PHP version PHP 5.6.24-0+deb8u1
Operating system Debian Wheezy
yii-httpclient 2.0.1

Thank you for your attention

No versions in this repo?

I look the versions tab (since I noticed composer said there was no 2.0.0) and the releases tab here is completely empty.

Is this expected?

Error yii\httpclient\XmlFormatter::itemTag

I create query with joins, then send(post) via http-client(xml), I getting error: "Getting unknown property: yii\httpclient\XmlFormatter::itemTag" like this.

$query = User::find()
                    ->with('orders')
                    ->where(['id' => $user_id['id']])
                    ->asArray()
                    ->one();
                $client = new Client([
                    'transport' => 'yii\httpclient\CurlTransport',
                    'requestConfig' => [
                        'format' => Client::FORMAT_XML
                    ],
                    'responseConfig' => [
                        'format' => Client::FORMAT_XML
                    ],
                ]);
                $response = $client->createRequest()
                    ->setMethod('post')
                    ->setUrl('http://site.com/orders/own')
                    ->setData($query)
                    ->send();

How to solve it?

Зачем?

Ну правда, просто интересно. Зачем был сделан? Есть же современные, качественные альтернативы.

Need to add Content-Length header then using addFile method

What steps will reproduce the problem?

$imageResponse = $this->getClient()->post('uploads')
->addFile('file', $imageFileName)
->send();

What's expected?

Expected success uploading

What do you get instead?

Receive error: curl error 18 - transfer closed with outstanding read data remaining

Additional info

method Request->prepareMultiPartContent do not generate Content-Length header

Q A
Yii vesion 2.0.9
PHP version 5.6.19
Operating system Debian x86

How do I specify the HTTP request version to 1.1

I am trying to make a REST API request to Azure Blob service and I get an UnsupportedHttpVersion error when making the call using the httpclient extension. This is the code I use

  $client = new Client(['baseUrl' => $uri]);
  //    $client = new Client();
    $request = $client->createRequest()
            ->setUrl($urlPath)
            ->setHeaders( [
                'x-ms-date' => $dateTime,
                'x-ms-version' => '2013-08-15',
                'Authorization' => $auth,
            ] )
            ->setMethod( 'GET' );
    var_dump($request);
    $response = $request->send();

When I make the same request from a POSTMAN REST client, it works perfectly and it says HTTP1.1 when I see what it sends. But I am not sure how I set this using this extension.

Any ideas?

Q A
Yii vesion 2.0
PHP version 5.5
Operating system Ubuntu

Fatal error: Uncaught Error: Class 'Yii' not found

What steps will reproduce the problem?

<?php
require __DIR__ . '/vendor/autoload.php';

use yii\httpclient\Client;

$client = new Client(['baseUrl' => 'http://example.com/api/1.0']);

What's expected?

Client object creation.

What do you get instead?

Fatal error: Uncaught Error: Class 'Yii' not found in ...

Additional info

Q A
Yii vesion 2.0.9
PHP version 7.0.8-4
Operating system Ubuntu 16.04

The requested package yiisoft/yii2-httpclient could not be found in any version

E:\xampp\htdocs\html5\php\yii-advanced-app-2.0.6>composer require --prefer-dist yiisoft/yii2-httpclient "*"
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package yiisoft/yii2-httpclient could not be found in any version, there may be a typo in the package name.

Potential causes:

Read https://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, deleting ./composer.json.

If error WARNING is enable fopen break in case of connection failure

A better error handling is needed. In case of connection timeout fopen does a warning which is intercepted by yii2 and break execution
fopen(http://myfakeurl.com): failed to open stream: Connection timed out

yiisoft/yii2-httpclient/StreamTransport.php line 59

$stream = fopen($url, 'rb', false, $context);

I know that in production warning should be disabled but errors should be better handled, especially if is a connection error I need to know it so I can inform in some way the user.

Anyway during development I need warning enable and putting in the code an error_reporting(E_ERROR | E_PARSE) just before httpclient call is not nice.

Sending twice, got double params

What steps will reproduce the problem?

Sending twice, got double params? its a bug or not. I am not sure.

$client = new Client(['transport' => 'yii\httpclient\StreamTransport']); // same to setup yii\httpclient\CurlTransport
$request = $client->createRequest()
    ->setUrl('http://localhost')
    ->setMethod('get')
    ->setData(['k'=>'v']);
$request->send();
$request->send();
$request->send();

in access log file, I got:

"GET /?k=v HTTP/1.0" 200 41686 "-" "-"
"GET /?k=v&k=v HTTP/1.0" 200 41694 "-" "-"
"GET /?k=v&k=v&k=v HTTP/1.0" 200 41702 "-" "-"

What's expected?

Same requested params.

Additional info

Q A
Yii vesion 2.0.9
Yii http client 2.0.0
PHP version 5.6.20
Operating system OSX

Http cache (304 not modified)

Нужна добавить возможность кэширования ответа от сервера, с помощью http загаловков.
"yiisoft/yii2": "*" сейчас присутствует в зависимостях, поэтому для хранения можно использовать интерфейс yii\caching\Cache

PS у "yiisoft/yii2": "*" желательно указать фиксированую версию.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.