LoginSignup
1
0

More than 3 years have passed since last update.

HTTPURLConnectionでBasic認証を行う際の実装例

Last updated at Posted at 2021-04-13
private void basicAuthFunction() throws IOException, ParseException {
    HttpURLConnection connection = null;
    try {
        final URL url = new URL(config.getRequestUrl());
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + config.getEncodeAuthorization());
        connection.connect();

        streamFunction(connection);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

private void streamFunction(HttpURLConnection connection) throws IOException, ParseException {
    try (final InputStream stream = connection.getInputStream();
         final BufferedReader reader = new BufferedReader(
                 new InputStreamReader(stream, StandardCharsets.UTF_8))) {

        final StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        final JSONObject obj = (JSONObject) new JSONParser().parse(builder.toString());
        final JSONObject data = (JSONObject) obj.get("data");
    }
}

参考

StringBuilderとStringBufferの違い -Qiita

1
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
1
0