httpurlconnection发送post请求头
时间: 2023-10-16 18:10:27 浏览: 100
https发送post请求
5星 · 资源好评率100%
下面是使用HttpURLConnection发送POST请求的示例代码:
```
try {
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
String input = "{\"username\":\"testuser\",\"password\":\"testpass\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes("UTF-8"));
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
```
在这个示例中,我们创建一个URL对象,然后使用URL.openConnection()方法打开一个HttpURLConnection连接。我们设置请求方法为POST,并设置Content-Type和Accept请求头。然后,我们调用setDoOutput(true)方法,表示我们要向服务器发送数据。我们将数据写入OutputStream中,并调用flush()方法确保所有数据都被发送。最后,我们读取服务器的响应,并输出到控制台上。最后,我们断开连接。
阅读全文