post java_Java发送post方法详解
时间: 2024-01-19 12:02:58 浏览: 27
Java发送POST请求的步骤如下:
1. 创建一个URL对象,该对象表示了要请求的URL。
2. 创建一个URLConnection对象,该对象表示了URL对象的连接。
3. 设置URLConnection对象的一些属性,例如请求方法、请求头等等。
4. 打开URLConnection连接,并且向URLConnection对象中写入请求参数。
5. 调用URLConnection对象的getInputStream()方法获取服务器的响应结果。
6. 对服务器的响应结果进行处理。
下面是一个Java发送POST请求的示例代码:
```java
import java.io.*;
import java.net.*;
public class PostDemo {
public static void main(String[] args) throws Exception {
String urlStr = "http://example.com/post";
String paramStr = "param1=value1¶m2=value2";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(paramStr.length()));
// 打开连接,并且向URLConnection对象中写入请求参数
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(paramStr.getBytes());
os.flush();
os.close();
// 获取服务器的响应结果
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
// 关闭流和连接
br.close();
is.close();
conn.disconnect();
}
}
```
在上面的代码中,我们首先创建了一个URL对象表示要请求的URL,然后创建了一个HttpURLConnection对象表示URL对象的连接。
之后,我们设置了请求方法为POST,并且设置了请求头,接着调用conn.setDoOutput(true)表示打开连接,并且向URLConnection对象中写入请求参数,然后将参数写入连接的输出流中。
最后,我们获取服务器的响应结果,并且对其进行处理。处理完毕后,我们关闭流和连接。