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 Java.net.JarURLConnection用法及代码示例
- Java Java.io.BufferedInputStream.available()用法及代码示例
- Java Java.io.BufferedInputStream.close()用法及代码示例
- Java Java.io.BufferedInputStream.read()用法及代码示例
- Java Java.io.BufferedInputStream.reset()用法及代码示例
- Java Java.io.BufferedInputStream.skip()用法及代码示例
- Java Java.io.BufferedOutputStream.flush()用法及代码示例
- Java Java.io.BufferedOutputStream.Write()用法及代码示例
- Java Java.io.BufferedReader.Close()用法及代码示例
- Java Java.io.BufferedReader.mark()用法及代码示例
- Java Java.io.BufferedReader.markSupported()用法及代码示例
- Java Java.io.BufferedReader.read()用法及代码示例
- Java Java.io.BufferedReader.readline()用法及代码示例
- Java Java.io.BufferedReader.ready()用法及代码示例
- Java Java.io.BufferedReader.reset()用法及代码示例
- Java Java.io.BufferedReader.skip()用法及代码示例
- Java Java.io.BufferedWriter.close()用法及代码示例
- Java Java.io.BufferedWriter.flush()用法及代码示例
- Java Java.io.BufferedWriter.newLine()用法及代码示例
- Java Java.io.BufferedWriter.write()用法及代码示例
- Java Java.io.ByteArrayInputStream.available()用法及代码示例
- Java Java.io.ByteArrayInputStream.close()用法及代码示例
- Java Java.io.ByteArrayInputStream.mark()用法及代码示例
- Java Java.io.ByteArrayInputStream.read()用法及代码示例
- Java Java.io.ByteArrayInputStream.reset()用法及代码示例
注:本文由纯净天空筛选整理自佚名大神的英文原创作品 Java.net.HttpURLConnection Class in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。