Java Java类
HttpURLConnection 类是直接从 URLConnection 类扩展而来的抽象类。它包括其父类的所有功能以及额外的 HTTP 特定功能。 HttpsURLConnection 是另一个用于更安全的 HTTPS 协议的类。
它是Java开发人员与 Web 服务器交互的流行选择之一,android 开发团队已正式建议尽可能使用它。稍后我们将说明一个交互式应用程序的简单实现,该应用程序使用 Microsoft 情感 API 使用 HttpURLConnection 类的方法从图像中检索情感分数。
构造函数
- HttpURLConnection(URL u):构造到指定 URL 的 httpurl 连接
方法(除了在 URLConnection 类中)
Method | Action performed |
---|---|
disconnect() | Indicated that requests to the server are highly unlikely in the future. |
getErrorStream() | Gets the error stream if the server cannot be connected or some error occurred. It can contain information about how to fix the error from the server. |
getFollowRedirects() | Returns true or false depending on automatic redirection or not. |
getHeaderField() | Returns the nth header field, or null if it does not exist. It overrides the getHeaderField method of URLConnection class. |
getInstanceFollowRedirects() | Returns true or false depending on whether automatic instance redirection is set or not. |
getPermission() | Retrieves the permission required to connect to a destination host and port. |
getResponseCode() | Used to retrieve the response status from server. |
getResponseMessage() | Retrieves the response message. |
getRequestMethod() | Returns the request method. |
setInstanceFollowRedirects() | Sets whether response code requests be redirected automatically by this instance of HTTP URL connection. It overrides the more generic setFollowRedirects() |
setRequestMethod() | Used to set the request method. Default is GET |
setFixedLengthStreamingMode() | Used to set the length of content written on outputstream if it is known in advance. |
setFollowRedirects() | Sets whether a 3xx response code request be redirected automatically or not. |
setChunkedStreamingMode() | Used when the content length is not known. Instead of creating a buffer of fixed length and writing it to a server, content is broken into chunks and then written. Not all servers support this mode. |
usingProxy() | Returns true if connection is established using a proxy, else 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() 等)时,它都会隐含地完成。
写入服务器:一旦我们获得到服务器的输出流,我们就将我们的图像上传到服务器进行处理。
从服务器读取响应:获取输入流后,我们使用缓冲读取器从服务器输出结果。
执行:
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.