4
0

More than 1 year has passed since last update.

Apacheのhttpclientを利用してServiceNow REST API( Table API)をJavaでたたく方法

Last updated at Posted at 2021-12-16

前記事

ここではJavaのプレーンなものでGETを実行しました。

Apacheのhttpclientを利用してGETを実行

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class App {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        getMethodByApache();
    }

    private static void getMethodByApache() throws ClientProtocolException, IOException {
        // ユーザーIDやパスワードは適切なものに書き換えてください
        String user = "admin";
        String pass = "xxxx";
        // URLは適切なものに書き換えてください
        String url = "https://xxxxxxx.service-now.com/api/now/table/incident?sysparm_limit=1";

        HttpGet request = new HttpGet(url);
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Accept", "application/json");
        request.addHeader("user", user
                + ":"
                + pass);
        String authString = getAuthorizationString(user, pass);
        request.addHeader("Authorization", "Basic "
                + authString);
        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(request);
        int httpStatusCode = response.getStatusLine().getStatusCode();
        if (httpStatusCode == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        }
    }

    private static String getAuthorizationString(String user, String password) {
        Charset charset = StandardCharsets.UTF_8;
        String userPassword = user
                + ":"
                + password;
        //byte[] authEncodedBytes = Base64.encodeBase64(userPassword.getBytes());
        byte[] authEncodedBytes = Base64.getEncoder().encode(userPassword.getBytes(charset));
        String authString = new String(authEncodedBytes);
        return authString;
    }

}

pom.xmlについて

Mavenを使っていたのでライブラリはpom.xmlで既存のものに対して以下のように追記した。

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
4
0
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
4
0