如何用Java实现简单的HTTP GET/POST请求?
时间: 2024-12-26 10:29:38 浏览: 8
在Java中,我们可以使用java.net包下的HttpURLConnection或者更现代的Apache HttpClient库来发送HTTP GET和POST请求。这里我将提供一个基本的使用HttpURLConnection的例子:
**GET请求:**
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleHttpClient {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/resource";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("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(response.toString());
}
}
```
**POST请求:**
```java
import java.io.OutputStream;
import java.io.IOException;
public class SimpleHttpPostRequest {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api/resource";
String postData = "param1=value1¶m2=value2"; // 你的数据
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true); // 告诉服务器我们有数据需要写入
try(OutputStream os = con.getOutputStream()) {
byte[] bytes = postData.getBytes("UTF-8");
os.write(bytes, 0, bytes.length);
}
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
}
}
```
记得替换上述代码中的URL为实际的目标地址,并处理可能的异常。
阅读全文