0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaでHTTP通信できるか簡易的にテスト

Posted at

はじめに

とりあえずさらっと、Javaで通信できるのかテストしてみたかったときに作成しました。成功した場合、GETリクエストの取得内容を出力します。

ソース

Test.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {

    public static void main(String[] args) throws IOException {

        String urlString = "https://www.google.com"; // アクセスしたいURLを指定
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setRequestMethod("GET"); // GETリクエストを指定

            int responseCode = connection.getResponseCode(); // 通信
            System.out.println("Response Code : " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { // 正常にレスポンスが返ってきた場合
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    System.out.println(response.toString());
                }
            } else {
                System.out.println("GET request not worked");
            }
        } finally {
            connection.disconnect(); // コネクションをクローズ
        }
    }
}

実行手順

以下を参考に、Java JDKを事前にインストールしておきましょう。
https://codeforfun.jp/how-to-install-java-jdk-on-windows-and-mac/

①Test.javaを作成する。ソースのクラス名とファイル名は一致させる必要があります。
②コマンドプロンプトを開き、Javaファイルが保存されているディレクトリに移動します。
➂javacコマンドを実行してコンパイルが成功すると、Test.classファイルが生成されます。
④javaコマンドを実行してプログラムを実行します。

cd Javaファイルが保存されているディレクトリ
javac Test.java
java Test
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?