如何使用Java进行HTTP请求:GET/POST示例
在Java中,我们可以使用java.net.HttpURLConnection
或者更高级的库如OkHttp
来执行HTTP请求。
以下是一个使用HttpURLConnection
进行GET和POST请求的示例:
- GET请求示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetExample {
public static void main(String[] args) {
String urlStr = “http://example.com“; // 你要访问的URL
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 检查连接状态,如果成功则返回响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容(以字符串形式)
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
String inputLine;
StringBuilder contentSoFar = new StringBuilder();
while ((inputLine = in.readLine()) != null)) {
contentSoFar.append(inputLine);
}
System.out.println("Response Content: " + contentSoFar.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. POST请求示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostExample {
public static void main(String[] args) {
String urlStr = "http://example.com/api"; // 你要访问的URL
String postData = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; // 要发送的数据
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 选择Post数据的类型(这里我们使用application/json)
connection.setDoOutput(true);
// 将要发送的数据写入到输出流中
byte[] bytes = postData.getBytes();
OutputStream outputStream = connection.getOutputStream();
outputStream.write(bytes);
// 检查连接状态,如果成功则返回响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
String inputLine;
StringBuilder contentSoFar = new StringBuilder();
while ((inputLine = in.readLine()) != null)) {
contentSoFar.append(inputLine);
}
System.out.println("Response Content: " + contentSoFar.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上就是使用Java进行HTTP GET和POST请求的基本示例。
还没有评论,来说两句吧...