Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
26
Help us understand the problem. What is going on with this article?
@n0bisuke

CakePHPのHttpSocketでHTTPリクエスト

More than 5 years have passed since last update.

久々にPHPを触ってHTTP通信をやろうとしたらCakePHPで簡単な方法があったのでメモ
公式ドキュメント(英)より

CakePHPのバージョンは2.4です.
HttpSocketというメソッドを利用するっぽいです

POSTリクエストの場合

(ユーザー登録をする某APIへリクエスト)

$resultsにレスポンスの値が入ります.

post_controller.php
$url = 'http://example.com/users/add';
$data = array(
    'username' => "yourename",
    'pass' => "パスワード",
);

App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();
$results = $HttpSocket->post($url, $data);
debug($results);

GETリクエストの場合

(問題を取得する某API)

$resultsにレスポンスの値が入ります.

get_controller.php
$url = 'http://example.com/problems/index.json';
$data = array(
    'limit' => 100,
    'grade' => 3
);

App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();
$results = $HttpSocket->get($url, array($data));
debug($results);

/*おまけ jsonの場合は$results->bodyに対してjson_decode()すると良いっぽです.*/
$response = json_decode($results->body);
26
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
n0bisuke
プロトタイピング専門スクール「プロトアウトスタジオ」で教えたりしてます。 プロフ -> https://dotstud.io/members/n0bisuke
dotstudio
全ての人がモノづくりを楽しむ世界を目指して活動しています。 ( https://dotstud.io ) プロトタイピングスクールの運営をしています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
26
Help us understand the problem. What is going on with this article?