java https post
时间: 2023-11-01 20:54:15 浏览: 26
下面是使用 Java 进行 HTTPS POST 请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpsPostExample {
public static void main(String[] args) throws IOException {
String url = "https://example.com/api/post";
String postData = "{\"name\":\"John Doe\",\"age\":30}";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(postData);
writer.flush();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
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());
}
}
```
这个示例代码向 `https://example.com/api/post` 发送了一个 JSON 格式的 POST 请求,并且设置了请求头的 Content-Type 为 `application/json`。在实际使用时,你需要将 `url` 和 `postData` 替换成你自己的 URL 和请求数据。
值得注意的是,这个示例代码使用的是 `HttpURLConnection` 类来发送 HTTPS 请求。在实际生产环境中,为了更加安全和便捷地发送 HTTPS 请求,你可以考虑使用第三方 HTTP 客户端库,比如 Apache HttpClient 或 OkHttp。