3
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2021-12-20

前記事

GETに関しては以下の記事を参照

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

package jp.co.worksap.company.apitest;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class App {

    public static void main(String[] args)
            throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        postMethodByApache();
    }

    private static void postMethodByApache() throws ClientProtocolException, IOException {
        // ユーザーIDやパスワードは適切なものに書き換えてください
        String user = "admin";
        String pass = "xxxx";
        // sys_id、テーブル名、ファイルパス、URLは適切なものに書き換えてください
        String sys_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String tableNmae = "tablename";
        String filePath = "X:/xxxxx/xxxxx.xxx";
        String url = "https://xxxxx.service-now.com/api/now/attachment/upload";

        CloseableHttpClient httpclient = HttpClients.createDefault();
        MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
        entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entitybuilder.addTextBody("table_name", tableNmae);
        entitybuilder.addTextBody("table_sys_id", sys_id);
        entitybuilder.addBinaryBody("file", new File(filePath));
        HttpEntity mutiPartHttpEntity = entitybuilder.build();
        RequestBuilder reqbuilder = RequestBuilder.post(url);
        reqbuilder.setEntity(mutiPartHttpEntity);
        HttpUriRequest multipartRequest = reqbuilder.build();
        multipartRequest.addHeader("user", user
                + ":"
                + pass);
        String authString = getAuthorizationString(user, pass);
        multipartRequest.addHeader("Authorization", "Basic "
                + authString);
        HttpResponse httpresponse = httpclient.execute(multipartRequest);
        int httpStatusCode = httpresponse.getStatusLine().getStatusCode();
        if (httpStatusCode == 200
                || httpStatusCode == 201) {
            BufferedReader br = new BufferedReader(new InputStreamReader((httpresponse.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.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>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
3
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
3
0