LoginSignup
27
27

More than 5 years have passed since last update.

Jersey Client で POST

Last updated at Posted at 2015-01-21

概要

以前書いたnode.jsでPOSTする記事(Yahoo の API を node.js から利用する)をJersey Client (Jersey2) で実装しました。

実装例

短いコードなので、すべて貼り付けます。
<appid>にはアプリケーション登録をして取得したアプリケーションIDが入ります。

build.gradle
apply plugin: 'java'

sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

if (!hasProperty('mainClass')) {
    ext.mainClass = 'com.example.Main'
}

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.glassfish.jersey.core:jersey-client:2.15'
}
Main.java
package com.example;

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;

public class Main {

    public static void main(String[] args) {
        // For HTTPS
//        System.setProperty("jsse.enableSNIExtension", "false");

        // POST パラメータ
        MultivaluedHashMap<String, String> formParams = new MultivaluedHashMap<>();
        formParams.putSingle("sentence", "東京ミッドタウンから国立新美術館まで歩いて5分で着きます。");
        formParams.putSingle("output", "xml");

        String result = ClientBuilder.newClient()
                .target("http://jlp.yahooapis.jp")
                .path("KeyphraseService/V1/extract")
                .request(MediaType.APPLICATION_XML_TYPE)
                .header("User-Agent", "Yahoo AppID:<appid>")
                .post(Entity.entity(formParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);

        // 標準出力にレスポンスを表示
        System.out.println(result);
    }
}

備考

  • HTTPSで通信する場合はSystem.setProperty("jsse.enableSNIExtension", "false")が必要でした。これについてはよく知らないので、気になる方は調べてください
  • このサンプルではContent-Type以外のヘッダが1つしかありませんでしたが、2つ以上付けたい場合はheaders()(doc: Invocation.Builder)を使用します

実装例 - レスポンスハンドリング -

上の例では、レスポンスボディの文字列をそのまま取り出していましたが、レスポンスのステータスコードやヘッダを取得したい場合もあります。このときはpost(Entity<?> entity)を使います。


import javax.ws.rs.core.Response; // 追加

...
        Response response = ClientBuilder.newClient()
                /* 略 */
                .post(Entity.entity(formParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

        // レスポンスコード
        int statusCode = response.getStatus(); // 200とか404とか

        // レスポンスボディ
        String body = response.readEntity(String.class);

注意

  • response.readEntity()は一度呼ぶと再度呼ぶことができません(java.lang.IllegalStateException: Entity input stream has already been closed.となります)

Links

27
27
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
27
27