请写出如下代码:java发送POST请求并设置Referer
时间: 2024-03-30 14:33:34 浏览: 20
以下是Java发送POST请求并设置Referer的示例代码:
```java
import java.net.*;
import java.io.*;
public class PostWithReferer {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api");
String referer = "http://example.com";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Referer", referer);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write("param1=value1¶m2=value2".getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
}
```
在上面的示例中,我们使用`HttpURLConnection`类发送POST请求。我们设置了请求方法为POST,并设置了Referer头。然后,我们使用`setDoOutput(true)`方法启用输出流,使用输出流将参数写入。接下来,我们使用`getInputStream()`方法获取响应,并使用`BufferedReader`读取响应。最后,我们关闭连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)