Java 使用 FormData 发送 POST 请求并携带 JSON 参数
以下是一个 Java 中使用 POST 请求发送 FormData 数据并带有 JSON 参数的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FormDataPostRequestExample {
public static void main(String[] args) throws Exception {
// 请求URL
String url = 'https://example.com/api';
// 构建JSON参数
String jsonParam = '{"name":"John", "age":30}';
// 创建URL对象
URL obj = new URL(url);
// 创建HttpURLConnection对象
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头信息
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 启用输入和输出流
con.setDoOutput(true);
con.setDoInput(true);
// 构建FormData参数
String formData = "data=" + jsonParam;
// 发送POST请求
OutputStream os = con.getOutputStream();
os.write(formData.getBytes("UTF-8"));
os.flush();
os.close();
// 获取请求结果
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response: " + response.toString());
}
}
在上面的示例中,首先构建了一个 JSON 参数 jsonParam,然后将其作为 FormData 参数的一个值进行发送。发送 POST 请求时,设置请求头信息为 application/x-www-form-urlencoded,并将 FormData 参数写入输出流中。最后获取请求结果并进行处理。
注意:在实际开发中,需要将 https://example.com/api 替换为实际的请求 URL,并根据实际需求调整请求头信息和参数的构建方式。
原文地址: https://www.cveoy.top/t/topic/peIR 著作权归作者所有。请勿转载和采集!