7

Java 网络请求方法整理基于 JDK 1.8

 3 years ago
source link: https://suiyia.github.io/2019/10/13/Java-%E7%BD%91%E7%BB%9C%E8%AF%B7%E6%B1%82%E6%96%B9%E6%B3%95%E6%95%B4%E7%90%86%E5%9F%BA%E4%BA%8E-JDK-1-8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java 网络请求方法整理基于 JDK 1.8

2019-10-13 36 评论 字数统计: 815(字) 阅读时长: 3(分)

写代码过程中发现自己对 Java 的一些 HTTP 请求方法不是很熟悉,也没有一个全局的概念框架,网上的一些博客使用的方法已经被 JDK 所抛弃。

于是简单整理下 Java 中常用的 HTTP 请求方法,以及它们的适用场景等,方便自己以后使用,本文基于 JDK 1.8。

这篇文章的作用很简单:

  1. 了解 Java 开发中常用的 HTTP 请求方法
  2. 了解这些方法的适用场景和注意事项
  3. 使用最新的方法,抛弃被添加 @Deprecated 注解的方法

1. 常用的 HTTP 请求方法

  • Socket:又称套接字,它工作在传输层,是所有应用层 HTTP 请求的底层实现。通过 ip 地址 + 端口号 即可实现网络通信

  • HttpURLConnection:继承了抽象类 URLConnection,源码中它定义了一些网络请求的返回码;也能够对 HTTP 请求做一些参数调整,例如使用 POST 请求、使用代理

  • HttpClient:是 Apache 下的子项目,使用时需要引入第三方 org.apache.httpcomponents.httpclient.jar 包,它对 HTTP 请求的一些方法封装的更多,造好的轮子,使用也更加方便

2. 各个 HTTP 请求方法示例

  1. Socket
public static void SocketDemo(URL url,String content){

try {
url = new URL("https://www.apiopen.top");
String path = "/weatherApi?city=%E6%AD%A6%E6%B1%89";
String host = url.getHost();
int port = 80; // 请求的 端口号
Socket socket = new Socket(host,port);
// 需要添加方法头,不然无法正确运行
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(),"utf-8");
osw.write("GET " + path + " HTTP/1.1\r\n");
osw.write("Host: " + host + " \r\n");
osw.write("Connection: Keep-Alive\r\n");
osw.write("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
osw.write("\r\n");
// 获取响应结果并输出
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readLine;
StringBuffer stringBuffer = new StringBuffer();
while ((readLine = reader.readLine()) != null) {
stringBuffer.append(readLine);
}
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}

}
  1. HttpURLConnection
public static void HttpURLConnection(URL url, String content) {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // 表示 getOutput() 的时候能起作用
connection.setDoOutput(true); // 表示 getInput() 的时候能起作用
connection.setUseCaches(false); // 不使用缓存
connection.setRequestMethod("POST"); // POST 请求

OutputStream outputStream = connection.getOutputStream();
outputStream.write(content.getBytes("UTF-8"));
outputStream.close();
// 获取响应结果并输出
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String readLine;
StringBuffer stringBuffer = new StringBuffer();
while ((readLine = reader.readLine()) != null) {
stringBuffer.append(readLine);
}
System.out.println(stringBuffer.toString());
} catch (MalformedURLException e) {
e.printStackTrace();

} catch (IOException e) {
e.printStackTrace();
}
}
  1. HttpClient
public static void HTTPClient(URL url,String content){
try {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url.toString()); // 执行 POST 请求,GET 请求有 HttpGet
CloseableHttpResponse response = (CloseableHttpResponse) client.execute(post); // 得到返回结果
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
}

Main 方法

public static void main(String[] args) {
try {
URL url = new URL("https://www.apiopen.top/weatherApi?city=%E6%AD%A6%E6%B1%89");
String content = "123";
HttpURLConnection(url, content);
HTTPClient(url,content);
SocketDemo(url,content);

} catch (MalformedURLException e) {
e.printStackTrace();
}
}

上面各个方法适用场景

  • 上面三个方法返回结果都是一样的,看代码量都知道使用哪个好,时间紧迫的时候直接用别人造好的轮子很有必要

  • 但是想提升内功,建议先学习 Socket 通信等知识,对自己以后的提升帮助会很大,机会总是留给有意无意有准备的人


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK