java 怎么实现post和get请求
时间: 2024-10-22 09:22:46 浏览: 17
Http.zip_java http post
在Java中,通常我们会使用HTTP客户端库如`java.net.HttpURLConnection`或者第三方库如`Apache HttpClient`或`OkHttp`来发送POST和GET请求。以下是基本的示例:
**使用HttpURLConnection发送GET请求:**
```java
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println(content.toString());
} else {
System.err.println("Request failed with code " + responseCode);
}
```
**使用HttpURLConnection发送POST请求(包含表单数据):**
```java
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true); // 设置可以输出数据
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try (OutputStream os = conn.getOutputStream()) {
byte[] data = ("key1=value1&key2=value2").getBytes(StandardCharsets.UTF_8);
os.write(data);
os.flush();
}
int responseCode = conn.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// ... 同样处理响应...
conn.disconnect();
```
**使用OkHttp发送GET请求:**
```java
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/api")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
```
**使用OkHttp发送POST请求:**
```java
FormBody.Builder bodyBuilder = new FormBody.Builder();
bodyBuilder.add("key1", "value1");
bodyBuilder.add("key2", "value2");
RequestBody requestBody = bodyBuilder.build();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/api")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
```
阅读全文