# AdvancedHTTPプラグイン

テスト環境 ( バージョン番号 ) : [3.3.0](https://github.com/silkimen/cordova-plugin-advanced-http/releases/tag/v3.3.0)

{% hint style="info" %}
このプラグインの詳細は、[こちら ( GitHub )](https://github.com/silkimen/cordova-plugin-advanced-http) をご確認ください。
{% endhint %}

このプラグインでは、グローバルオブジェクト「`cordova.plugin.http`」のAPIを使用し、HTTPサーバーとの通信を行います。&#x20;

このオブジェクトは、グローバルスコープに属していますが、使用できるのは、`deviceready` イベントの発火後になります。

```javascript
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(cordova.plugin.http);
}
```

## プラグインID

```
cordova-plugin-advanced-http
```

## プラグインの追加方法(Monaca上での操作)

1. Monaca クラウド IDE から`設定 → Cordova プラグインの管理` を選択します。
2. 利用可能なプラグイン 項目の `AdvancedHTTP` プラグインにカーソルを置き、`有効`ボタンをクリックします。

## 機能

* iOSやAndroidのネイティブ機能を用いてHTTP通信を行います。
* Javascript で`fetch API` などを用いた場合に比べて以下のような利点があります。
  * CORSエラーの回避

## APIの解説

### 基本的なAPI

以下の基本的なAPIについて解説します。

* sendRequest
* setDataSerializer
* get
* post

#### **sendRequest**

```
cordova.plugin.http.sendRequest(url, options, success, error)
```

* 指定した`url`にHTTPリクエストを送信します。
* `options`に様々なパラメータを設定します。
  * `method`: HTTPメソッド
  * `headers`: HTTPヘッダ
  * `param`: クエリ文字列(主にgetメソッドで使用)
  * `data`: リクエストボディのデータ。形式はserializerで指定(post,putなどのメソッドで使用)
  * `serializer`: データ形式の指定。詳細は後述の`setDataSerializer`参照
  * その他のパラメータについては[Cordova Advanced HTTP plugin](https://github.com/silkimen/cordova-plugin-advanced-http)参照
* `success`: 成功時のコールバック
* `error`: エラー時のコールバック

例

```javascript
const options = {
  method: "post",
  headers: { "Accept": "application/json" },
  data: { "key1": "123", "key2": "abc" },
  serializer: "json"
};

cordova.plugin.http.sendRequest("https://example.com", options, (response) => {
  // success
  console.log(response.status);
}, (response) => {
  // error
  console.log(response.status);
  console.log(response.error);
});
```

#### **setDataSerializer**

```
cordova.plugin.http.setDataSerializer(serializer)
```

* 送信するデータの形式を指定します。
* `sendRequest API`の options.serializerで指定するのと同等です。
* POST/PUT/PATCHメソッドに対応しています。
* 指定できる値:
  * "urlencoded"
  * "json"
  * "utf8"
  * "multipart"
  * "raw"

例1: `serializer`="urlencoded"

```javascript
cordova.plugin.http.setDataSerializer("urlencoded");
cordova.plugin.http.sendRequest(url, {
    "method": "post",
    // "serializer": "urlencoded", // optionでの指定も可能
    "data": { "key1": "123", "key2": "abc" }
}, success, error);
```

* `key1=123`, `key2=abc` の値がフォームデータとして送信されます。(`Content-Type: application/x-www-form-urlencoded`での送信に相当)

例2: `serializer`="json"

```javascript
cordova.plugin.http.setDataSerializer("json");
cordova.plugin.http.sendRequest(url, {
    "method": "post",
    // "serializer": "json", // optionでの指定も可能
    "data": { "key1": "123", "key2": "abc" }
}, success, error);
```

* リクエストボディにJSONデータを載せて送信します。

その他のデータ形式については[Cordova Advanced HTTP plugin](https://github.com/silkimen/cordova-plugin-advanced-http)を参照してください。

#### **get**

```
cordova.plugin.http.get(url, param, headers, success, error)
```

* GETリクエストを送信します。
* `sendRequest API`で`method: "get"`を指定した場合と同等の機能です。
* 第２引数にクエリ文字列を指定します。

例

```javascript
  cordova.plugin.http.get(url,
  {
    // query parameters
    "key1": "123",
    "key2": "abc"
  }, {
    // headers
  }, success, error);
```

#### **post**

```
cordova.plugin.http.post(url, data, headers, success, error)
```

* POSTリクエストを送信します。
* `sendRequest API`で`method: "post"`を指定した場合と同等の機能です。
* 第２引数にデータを指定します。データの送信形式は`setDataSerializer API`で指定します。

例

```javascript
cordova.plugin.http.setDataSerializer("urlencoded");
cordova.plugin.http.post(url,
{
    // data
    "key1": "123",
    "key2": "abc"
}, {
    // headers
}, success, error);
```

### 高度な使い方

`AdvancedHTTP`プラグインにはその他にも様々なAPIが用意されています。

* put / patch / delete / head / options
* uploadFile / downloadFile
* getBasicAuthHeader
* useBasicAuth
* setRequestTimeout
* setConnectTimeout (Android Only)
* setReadTimeout (Android Only)
* setFollowRedirect
* getCookieString
* setCookie
* clearCookies
* setServerTrustMode
* setClientAuthMode
* removeCookies

これらのAPIの詳細については[Cordova Advanced HTTP plugin](https://github.com/silkimen/cordova-plugin-advanced-http)を参照してください。

## サンプル

### fetch APIとの比較

例: POSTリクエストを送信する場合

fetch API

```javascript
const url = "https://example.com/";
const method = "POST";
const body = "key1=123&key2=abc";
const headers = {
    "Accept": "application/json",
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
};
fetch(url, {
    method,
    headers,
    body
}).then((response) => {
    // convert to json
    return response.json();
}).then((result) => {
    console.log(result);
    alert(JSON.stringify(result));
});
```

AdvancedHTTP

```javascript
const url = "https://example.com/";
const data = {
    "key1": "123",
    "key2": "abc"
};
const headers = {
    "Accept": "application/json",
};
cordova.plugin.http.setDataSerializer("urlencoded");
cordova.plugin.http.post(url, data, headers, (response) => {
    console.log(response);
    alert(JSON.stringify(response));
}, (response) => {
    // error
});
```

### サンプルアプリ

この記事に記載されたサンプルコードを実装したアプリケーションを公開しています。 Monacaにプロジェクトをインポートしてご利用ください。

[サンプルアプリのインポート](https://monaca.mobi/ja/directimport?pid=639932bee788852269d3cea4)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ja.docs.monaca.io/reference/third_party_phonegap/advancedhttppuraguin.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
