使用JAVA代码实现POST发送application/x-www-form-urlencoded请求 携带JSESSIONID
时间: 2024-06-12 14:10:30 浏览: 275
可以使用Java的HttpURLConnection类来实现POST发送application/x-www-form-urlencoded请求,同时携带JSESSIONID。具体代码如下:
```java
import java.io.*;
import java.net.*;
public class PostRequest {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
String sessionId = "JSESSIONID=1234567890";
String data = "param1=value1¶m2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头部信息
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Cookie", sessionId);
// 启用输出流
con.setDoOutput(true);
// 将参数写入请求体
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(data);
writer.flush();
writer.close();
// 发送请求并获取响应
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应结果
System.out.println(response.toString());
}
}
```
阅读全文