用JAVA代码编写HttpURLConnection 发送get和post请求的方法
时间: 2024-03-16 17:42:24 浏览: 100
下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求的示例:
1. 发送 GET 请求
```java
import java.net.*;
import java.io.*;
public class HttpGet {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
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 (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 发送 POST 请求
```java
import java.net.*;
import java.io.*;
public class HttpPost {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
String input = "{\"username\":\"test\",\"password\":\"test\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
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 (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。
阅读全文