java post 数组
时间: 2023-10-22 12:00:01 浏览: 85
要使用 Java 进行 POST 请求并发送数组,可以使用 HttpURLConnection 类。以下是一个示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ArrayPOST {
public static void main(String[] args) throws Exception {
// 要发送的数组
int[] array = {1, 2, 3, 4, 5};
// 创建 URL 对象并设置请求方法为 POST
URL url = new URL("http://example.com/post_array");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/json");
// 将数组转换为 JSON 字符串并转换为字节数组
String json = "[";
for (int i = 0; i < array.length; i++) {
if (i > 0) json += ", ";
json += array[i];
}
json += "]";
byte[] data = json.getBytes("UTF-8");
// 设置请求体长度
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// 启用输出流并写入请求体
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(data);
os.flush();
os.close();
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String response = "";
String line;
while ((line = in.readLine()) != null) {
response += line;
}
in.close();
// 输出响应内容
System.out.println(response);
}
}
```
在以上代码中,我们使用了 `HttpURLConnection` 类来创建 HTTP 连接。我们设置了请求头 `Content-Type` 为 `application/json`,表示请求体中的数据是 JSON 格式的。我们将数组转换为 JSON 字符串并写入请求体中,然后读取响应内容并输出。
阅读全文
相关推荐














