java http post请求代码
时间: 2024-05-13 07:08:08 浏览: 94
java http token请求代码实例
5星 · 资源好评率100%
下面是使用Java发送POST请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpPostExample {
public static void main(String[] args) {
try {
String url = "http://example.com/api";
String payload = "key1=value1&key2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置HTTP请求方法为POST
con.setRequestMethod("POST");
// 设置请求头信息
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 启用输出流
con.setDoOutput(true);
// 创建输出流写入POST请求参数
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(payload);
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());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,`url`为请求的URL地址,`payload`为POST请求的参数。在示例中,POST请求的参数是以`key1=value1&key2=value2`的形式拼接的,如果需要传递JSON数据,则可以将JSON序列化为字符串作为POST请求参数。
阅读全文