HttpURLConnection クラス から直接拡張された抽象クラスです。 URLConnectionクラス 。これには、親クラスのすべての機能と追加の HTTP 固有の機能が含まれています。 HttpsURLConnection は、より安全な HTTPS プロトコルに使用されるもう 1 つのクラスです。
これは、Web サーバーと対話するための Java 開発者の間で人気のある選択肢の 1 つであり、Android 開発チームは可能な限りこれを使用することを公式に提案しています。後で、Microsoft 感情 API を使用し、HttpURLConnection クラスのメソッドを使用して画像から感情スコアを取得する対話型アプリケーションの簡単な実装を説明します。
コンストラクタ
メソッド(URLConnectionクラス以外)
| 方法 | 実行されたアクション |
|---|---|
| 切断() | サーバーへのリクエストが将来発生する可能性は非常に低いことを示します。 |
| getErrorStream() | サーバーに接続できない場合、または何らかのエラーが発生した場合にエラー ストリームを取得します。サーバーからのエラーを修正する方法に関する情報が含まれる場合があります。 |
| getFollowRedirects() | 自動リダイレクトかどうかに応じて true または false を返します。 |
| getHeaderField() | n 番目のヘッダー フィールドを返すか、存在しない場合は null を返します。 URLConnection クラスの getHeaderField メソッドをオーバーライドします。 |
| getInstanceFollowRedirects() | 自動インスタンス リダイレクトが設定されているかどうかに応じて、true または false を返します。 |
| getPermission() | 宛先ホストとポートに接続するために必要な権限を取得します。 |
| getResponseCode() | サーバーからの応答ステータスを取得するために使用されます。 |
| getResponseMessage() | 応答メッセージを取得します。 |
| getRequestMethod() | リクエストメソッドを返します。 |
| setInstanceFollowRedirects() | 応答コード要求が HTTP URL 接続のこのインスタンスによって自動的にリダイレクトされるかどうかを設定します。より汎用的な setFollowRedirects() をオーバーライドします。 |
| setRequestMethod() | リクエストメソッドの設定に使用します。デフォルトはGETです |
| setFixedLengthStreamingMode() | 事前にわかっている場合、出力ストリームに書き込まれるコンテンツの長さを設定するために使用されます。 |
| setFollowRedirects() | 3xx 応答コード要求を自動的にリダイレクトするかどうかを設定します。 |
| setChunkedStreamingMode() | コンテンツの長さが不明な場合に使用されます。固定長のバッファを作成してサーバーに書き込むのではなく、コンテンツが複数のチャンクに分割されてから書き込まれます。すべてのサーバーがこのモードをサポートしているわけではありません。 |
| usingProxy() | プロキシを使用して接続が確立されている場合は true を返し、それ以外の場合は false を返します。 |
ヒント: 以下の実装をよりよく理解するには、この HttpURLConnection クラスを使用して URL を読み取る方法を理解しておくとよいでしょう。
図: プロセス全体は次のように簡単に理解できます。
以下のURLを使用してMicrosoft感情APIのサーバーに接続します
https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize
リクエストを発行するためのプロパティとメソッドを設定します。 このステップでは、リクエスト オブジェクトのメソッドとプロパティを設定します。まず、POSTとして呼び出されるリクエストメソッドとしてメソッドを設定します。また、User-Agent プロパティを設定して、予期しない応答タイプが原因でリクエストがサーバーによってブロックされないようにします。そうでなければ、どの Web ブラウザでも正常に動作します。
http get リクエストを発行します。 URL を作成し、HttpURLConnection オブジェクトを作成した後、実際にリクエストを発行する必要があります。これは connect() メソッドによって明示的に実行できます。これは、getOutputStream() などの応答メッセージを使用しようとするたびに暗黙的に行われます。
サーバーへの書き込み: サーバーへの出力ストリームを取得したら、処理のために画像をサーバーにアップロードします。
サーバーからの応答を読み取る: 入力ストリームを取得した後、bufferedreader を使用してサーバーから結果を出力します。
実装:
Java// Java Program to Illustrate Use // of HttpURLConnection Class // to Retrieve Emotion score of Image // Using Microsoft Emotion API // Importing required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.simple.JSONObject; // Main class // httpconclass class public class GFG { // Main driver method public static void main(String args[]) throws IOException { // Reading input via BufferedReader class BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String key = '833921b016964f95905442e0fab0c229'; JSONObject ezm; while (n-- > 0) { String image = br.readLine(); ezm = new JSONObject(); ezm.put('url' image); // Try block to check for exceptions try { // URL for microsoft cognitive server. URL url = new URL( 'https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize'); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // Setting the request method and // properties. con.setRequestMethod('POST'); con.setRequestProperty( 'Ocp-Apim-Subscription-Key' key); con.setRequestProperty('Content-Type' 'application/json'); con.setRequestProperty('Accept' 'application/json'); // As we know the length of our content // the following function sets the fixed // streaming mode length 83 bytes. If // content length not known comment the // below line. con.setFixedLengthStreamingMode(83); // Setting the auto redirection to true HttpURLConnection.setFollowRedirects(true); // Overriding the default value set by // the static method setFollowRedirect above con.setInstanceFollowRedirects(false); // Setting the doOutput to true for now con.setDoOutput(true); OutputStream out = con.getOutputStream(); // System.out.println(ezm.toString().getBytes().length); // Writing on the output stream out.write(ezm.toString().getBytes()); InputStream ip = con.getInputStream(); BufferedReader br1 = new BufferedReader( new InputStreamReader(ip)); // Printing the response code // and response message from server. System.out.println('Response Code:' + con.getResponseCode()); System.out.println( 'Response Message:' + con.getResponseMessage()); // Note: Uncomment the following line to // print the status of FollowRedirect // property // System.out.println('FollowRedirects:' // + // HttpURLConnection.getFollowRedirects()); // Printing the status of // instanceFollowRedirect property System.out.println( 'InstanceFollowRedirects:' + con.getInstanceFollowRedirects()); // Printing the 1st header field System.out.println('Header field 1:' + con.getHeaderField(1)); // Printing if usingProxy flag set or not System.out.println('Using proxy:' + con.usingProxy()); StringBuilder response = new StringBuilder(); String responseSingle = null; while ((responseSingle = br1.readLine()) != null) { response.append(responseSingle); } String xx = response.toString(); System.out.println(xx); } // Catch block to handle exceptions catch (Exception e) { // Display exception/s on console System.out.println(e.getMessage()); } } } }
出力:
Response Code:200 Response Message:OK FollowRedirects:true InstanceFollowRedirects:false Header field 1:no-cache Using proxy:false [{'faceRectangle':{'height':134'left':62'top':86'width':134}'scores':{'anger':4.105452E- 14'contempt':1.240792E-11'disgust':2.58925052E-11'fear':1.82401266E-17'happiness':1.0 'neutral':2.487733E-10'sadness':6.02089044E-14'surprise':2.665974E-12}}] 出力の説明: このプログラムをテストするには、処理する画像の数を指定し、画像の URL を指定する必要があります。サーバーが自動的に処理するため、コンテンツの長さのプロパティを設定しないままにすることもできますが、長さがわかっている場合は、それに応じて毎回変更します。 指定されたソース コードでは、コンテンツの長さが 83 バイトに設定されているため、そのサイズの URL を使用する必要があります。
Sample URL: https://media.geeksforgeeks.org/wp-content/uploads/Brad_Pitt.webp
注記: インタラクティブなアプリケーションであるため、オフライン プラットフォームで実行することをお勧めします。このアプリケーションを実行するには、JSON ライブラリもプロジェクトのビルド パスに含める必要があります。
クイズの作成