0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaでHTTPリクエストのPOSTメソッドでAPI呼び出しサンプル

Posted at

HTTPリクエストにてAPI呼び出し

OAuth認証などで取得したアクセストークンを用いて、
外部APIに対してJSONパラメータをリクエストする処理のサンプル

パラメータ説明

setTimeout() :タイムアウト値をセットするメソッド
"api.endpoint.co.jp :外部連携APIのエンドポインt"
accessToken :アクセストークン

処理

// URLオブジェクト作成
URL url =new URL(API_PATH);
//httpsコネクターをオープン
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// タイムアウト時間を設定
con.setConnectTimeout(setTimeout());
// メソッドをPOSTに設定
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
// リクエストヘッダーの追加
con.setRequestProperty("Host", "api.endpoint.co.jp");
con.setRequestProperty("Authorization", "Bearer " + accessToken);
con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
// 接続する
con.connect();
// リクエストボディへの書き込み
OutputStreamWriter os= new OutputStreamWriter(con.getOutputStream());
os.write(jsonParam);
os.close();
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?