當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.net.HttpURLConnection用法及代碼示例


HttpURLConnection 類是一個直接擴展自的抽象類URL連接類。它包含其父類的所有函數以及附加的 HTTP-specific 函數。 HttpsURLConnection 是另一個用於更安全的 HTTPS 協議的類。

它是 Java 開發人員與 Web 服務器交互的流行選擇之一,Android 開發團隊已正式建議盡可能使用它。稍後我們將演示一個交互式應用程序的簡單實現,該應用程序使用 Microsoft 情感 API 使用 HttpURLConnection 類的方法從圖像中檢索情感分數。

構造函數

  • HttpURLConnection(URL u):構造到指定 URL 的 httpurlconnection

Methods (Other than in URLConnection class)

方法 執行的操作
disconnect() 表明將來極不可能向服務器發出請求。
getErrorStream() 如果服務器無法連接或發生某些錯誤,則獲取錯誤流。它可以包含有關如何修複服務器錯誤的信息。
getFollowRedirects() 根據是否自動重定向返回 true 或 false。
getHeaderField() 返回第 n 個頭字段,如果不存在則返回 null。它重寫了 URLConnection 類的 getHeaderField 方法。
getInstanceFollowRedirects() 根據是否設置自動實例重定向返回 true 或 false。
getPermission() 檢索連接到目標主機和端口所需的權限。
getResponseCode() 用於從服務器檢索響應狀態。
getResponseMessage() 檢索響應消息。
getRequestMethod() 返回請求方法。
setInstanceFollowRedirects() 設置此 HTTP URL 連接實例是否自動重定向響應代碼請求。它覆蓋更通用的setFollowRedirects()
setRequestMethod() 用於設置請求方式。默認是獲取
setFixedLengthStreamingMode() 用於設置寫入輸出流的內容長度(如果事先已知)。
setFollowRedirects() 設置是否自動重定向 3xx 響應代碼請求。
setChunkedStreamingMode() 當內容長度未知時使用。內容不是創建固定長度的緩衝區並將其寫入服務器,而是被分成塊然後寫入。並非所有服務器都支持此模式。
usingProxy() 如果使用代理建立連接則返回 true,否則返回 false

Tip: It would be good to have understanding of how to read URL using this HttpURLConnection class for better understanding of below implementation.

圖解:整個過程可以簡單理解如下:

使用以下 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.jpg

Note: As it is an interactive application, it is advised to run it on offline platforms. JSON library should also be included in the build path of the project to run this application.



相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Java.net.HttpURLConnection Class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。