Java 实现application/x-www-form-urlencoded编码格式的POST请求
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FormUrlEncodedPost {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api/resource");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置为true,默认情况下,此属性为false,即在发送POST请求时通常不设置Content-Length
connection.setDoOutput(true);
// 构建请求体
String data = "param1=value1¶m2=value2";
byte[] outputInBytes = data.getBytes("UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(outputInBytes.length));
// 发送请求体
try(OutputStream os = connection.getOutputStream()) {
os.write(outputInBytes);
}
// 获取响应码和响应内容
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 处理响应内容...
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码演示了如何使用Java发送一个POST请求,其中请求体采用application/x-www-form-urlencoded
编码格式。首先创建了一个指向特定URL的HttpURLConnection
实例,然后设置请求方法为POST,并设置请求头Content-Type
为application/x-www-form-urlencoded
。接着构建了请求体数据,并通过连接的输出流发送数据。最后,获取响应码并打印,然后可以对响应内容进行处理,最后关闭连接以释放资源。
评论已关闭