实现POST(x-www-form-urlencoded)请求的过程如下所示:
- 构建URL和请求参数
- 创建URL对象和HttpURLConnection对象
- 设置请求头
- 写入请求参数
- 发起请求并接受服务器响应
以下为代码示例:
示例一
import java.net.*;
import java.io.*;
public class PostRequestExample {
public static void main(String[] args) {
try {
//构建URL和请求参数
String urlStr = "https://example.com/api";
String params = "name=value1&foo=bar";
//创建URL对象和HttpURLConnection对象
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求头
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
//写入请求参数
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
//发起请求并接受服务器响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//记录响应信息
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例二
import java.net.*;
import java.io.*;
public class PostRequestExample {
public static void main(String[] args) {
try {
//构建URL和请求参数
String urlStr = "https://example.com/api";
String firstName = "John";
String lastName = "Doe";
String email = "johndoe@example.com";
String params = "firstName=" + URLEncoder.encode(firstName, "UTF-8")
+ "&lastName=" + URLEncoder.encode(lastName, "UTF-8")
+ "&email=" + URLEncoder.encode(email, "UTF-8");
//创建URL对象和HttpURLConnection对象
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求头
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
//写入请求参数
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(params);
out.flush();
out.close();
//发起请求并接受服务器响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//记录响应信息
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码仅供参考,实际应用中需要根据具体的情况进行调整。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java 如何实现POST(x-www-form-urlencoded)请求 - Python技术站