java get请求简洁,Java 不依赖第三方实现 HTTP GET 和 POST 请求 ( 一 )

一般情况下,我们使用 Java 发起一个 HTTP 发起一个 GET 或 POST 请求,最先想到的是什么?

对,就是先找找看有没有啥现成的解决方案,然后,肯定就会想到 HTTPClient 这种大名鼎鼎的库

其实,对于一般的请求,Java 内置的包 java.net 就能够实现了。能不使用 HTTPClient 就不用呗

怎么说呢?我本人有极大的洁癖症,能少一点是一点

所以,接下来的案例,我们就不用什么 IDE 了,直接上一个纯文本编辑器,外加 Java 环境即可。

远程资源

既然是网络请求,肯定要远程资源,我们也进一步偷懒吧,直接使用 https://jsonplaceholder.typicode.com ,该网站提供了简单的 get / post / put / delete 端点 ( endpoint)

出于演示目的,我只使用 GET 和 POST 端点

源码文件

直接取个名字 GetAndPost.java 就好了

随便放在哪里,只要你能找到就好,然后输入以下内容调试下我们的 Java 环境

public class GetAndPost {

public static void main(String[] args) {

System.out.println("Hello World");

}

}

保存,然后在命令行中输入 javac GetAndPost.java && java GetAndPost 看看输出是否成功

$ javac GetAndPost.java && java GetAndPost

Hello World

引入包和添加方法原型

我们需要用到 java.net 包里的相关类来创建 HTTP 请求,需要用到 java.io 包里的相关类来读取请求的结果,所以需要引入这两个包

import java.io.*;

import java.net.*;

对于 GET 和 POST 请求,我们分别添加两个方法来实现,分别是

MyGETRequest(); // 用于实现 GET 请求

MyPOSTRequest(); // 用于实现 POST 请求

添加完后,所有的 GetAndPost.java 中的内容如下

GetAndPost.java

import java.io.*;

import java.net.*;

public class GetAndPost {

public static void MyGETRequest() throws IOException {}

public static void MyPOSTRequest() throws IOException {}

public static void main(String[] args) {

try {

GetAndPost.MyGETRequest(); // 用于实现 GET 请求

GetAndPost.MyPOSTRequest(); // 用于实现 POST 请求

} catch ( IOException e ) {

System.out.println(e);

}

}

}

MyGETRequest()

我们在 MyGETRequest() 对 https://jsonplaceholder.typicode.com/posts/1 发起一个 HTTP GET 请求

为了对 MyGETRequest() 输出的结果有个预期,我们先在浏览器中打开这个网址,得到的结果如下

{

"userId": 1,

"id": 1,

"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",

"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"

}

我们先来说说使用 java.net 包完成一个 HTTP GET 请求的一般流程

使用 java.net.URL 类创建一个 URL 类的实例 urlForGetRequest ,参数为要请求的网址

调用 URL 实例的 openConnection() 方法打开一个到远程服务器的连接 conection

然后对连接 conection 设置一些属性,比如调用 setRequestMethod() 设置请求方法,调用 setRequestProperty() 添加一些查询参数

设置完了属性之后,就可以调用连接的 getResponseCode() 发起请求并返回请求的响应状态码

判断返回的响应状态吗,如果为 200 则表示成功,然后就可以调用连接的 getInputStream() 获取输入流

有了输入流之后,就可以使用 java.io 包中的相关类读取响应的数据

其它的对响应数据的处理逻辑

遵循这个思路,MyGETRequest() 的实现大概如下

public static void MyGETRequest() throws IOException {

// 1. 创建 URL 实例

URL urlForGetRequest = new URL("https://jsonplaceholder.typicode.com/posts/1");

String readLine = null;

// 2. 打开到远程服务器的连接

HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();

// 3. 设置连接属性,比如请求方法和请求参数

conection.setRequestMethod("GET");

conection.setRequestProperty("userId", "a1bcdef"); // set userId its a sample here

// 4. 发起请求并获取响应的状态码

int responseCode = conection.getResponseCode();

// 5. 根据状态码作出一些判断,如果为 200 则表示成功

if (responseCode == HttpURLConnection.HTTP_OK) {

// 6. 使用 getInputStream() 获取输入流并读取输入流里的数据

BufferedReader in = new BufferedReader(

new InputStreamReader(conection.getInputStream()));

// 7. 其它处理逻辑,这里直接输出响应的数据

StringBuffer response = new StringBuffer();

while ((readLine = in .readLine()) != null) {

response.append(readLine);

}

in.close();

System.out.println("JSON String Result " + response.toString());

} else {

System.out.println("GET NOT WORKED");

}

}

使用 javac GetAndPost.java && java GetAndPost 命令运行结果如下

$ javac GetAndPost.java && java GetAndPost

JSON String Result { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}

得到的结果是不是我们直接在浏览器中访问的一样?

全部的源代码如下

import java.io.*;

import java.net.*;

public class GetAndPost {

public static void MyGETRequest() throws IOException {

// 1. 创建 URL 实例

URL urlForGetRequest = new URL("https://jsonplaceholder.typicode.com/posts/1");

String readLine = null;

// 2. 打开到远程服务器的连接

HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();

// 3. 设置连接属性,比如请求方法和请求参数

conection.setRequestMethod("GET");

conection.setRequestProperty("userId", "a1bcdef"); // set userId its a sample here

// 4. 发起请求并获取响应的状态码

int responseCode = conection.getResponseCode();

// 5. 根据状态码作出一些判断,如果为 200 则表示成功

if (responseCode == HttpURLConnection.HTTP_OK) {

// 6. 使用 getInputStream() 获取输入流并读取输入流里的数据

BufferedReader in = new BufferedReader(

new InputStreamReader(conection.getInputStream()));

// 7. 其它处理逻辑,这里直接输出响应的数据

StringBuffer response = new StringBuffer();

while ((readLine = in .readLine()) != null) {

response.append(readLine);

}

in.close();

System.out.println("JSON String Result " + response.toString());

} else {

System.out.println("GET NOT WORKED");

}

}

public static void MyPOSTRequest() throws IOException {}

public static void main(String[] args) {

try {

GetAndPost.MyGETRequest(); // 用于实现 GET 请求

GetAndPost.MyPOSTRequest(); // 用于实现 POST 请求

} catch ( IOException e ) {

System.out.println(e);

}

}

}

篇幅有限,POST 请求我们下一章节中再来讲解把

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnection或者HttpClient等类库来实现调用第三方API的GET和POST请求GET请求示例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GetRequestExample { public static void main(String[] args) { try { URL url = new URL("https://api.example.com/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` POST请求示例: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import java.nio.charset.StandardCharsets; public class PostRequestExample { public static void main(String[] args) { try { URL url = new URL("https://api.example.com/data"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String requestBody = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; try (OutputStream os = conn.getOutputStream()) { byte[] input = requestBody.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这里以调用JSON格式的API接口为例,请求头中设置了Accept为"application/json",请求体中的数据也是JSON格式的。POST请求需要设置请求方法为"POST",同时需要设置请求头中的Content-Type为"application/json",并且需要将请求体数据写入到请求输出流中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值