21xrx.com
2024-12-22 21:55:42 Sunday
登录
文章检索 我的文章 写文章
最近我在学习Java编程
2023-06-15 17:23:19 深夜i     --     --
HttpURLConnection GET POST下面我来简单介绍一下它们的作用:

最近我在学习Java编程,其中最有趣的部分是如何调用API接口。API是应用程序编程接口的缩写,它允许不同的软件之间进行交互。这些API接口可以是公共的,也可以是私有的。在学习Java调用API接口的过程中,我了解到了三个

1. HttpURLConnection

HttpURLConnection是Java中一个用于发送HTTP请求的类。使用HttpURLConnection,我们可以方便地发送GET、POST和其他类型的HTTP请求到API接口。下面是一个简单的例子,展示如何使用HttpURLConnection发送GET请求:


URL url = new URL("https://api.example.com/getdata");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("GET");

int responseCode = con.getResponseCode();

System.out.println("HTTP response code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();

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

  response.append(inputLine);

}

in.close();

System.out.println("HTTP response body: " + response.toString());

2. GET

GET是HTTP请求的一种类型,用于从API接口获取数据。GET请求发送的参数要求出现在URL的query string中。下面是一个简单的例子,展示如何使用GET请求从API接口获取数据:


URL url = new URL("https://api.example.com/getdata?param1=value1&param2=value2");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("GET");

int responseCode = con.getResponseCode();

System.out.println("HTTP response code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();

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

  response.append(inputLine);

}

in.close();

System.out.println("HTTP response body: " + response.toString());

3. POST

POST是HTTP请求的一种类型,用于向API接口提交数据。POST请求发送的参数要求出现在请求体中。下面是一个简单的例子,展示如何使用POST请求向API接口提交数据:


URL url = new URL("https://api.example.com/submitdata");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("POST");

String data = "param1=value1&param2=value2";

con.setDoOutput(true);

DataOutputStream out = new DataOutputStream(con.getOutputStream());

out.writeBytes(data);

out.flush();

out.close();

int responseCode = con.getResponseCode();

System.out.println("HTTP response code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();

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

  response.append(inputLine);

}

in.close();

System.out.println("HTTP response body: " + response.toString());

以上就是我的Java调用API接口学习笔记,希望能对初学者有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复