在Java中发送POST请求到接口,可以使用Java内置的`HttpURLConnection`类或者第三方库如Apache HttpClient。以下是使用`HttpURLConnection`发送POST请求的示例代码:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api/endpoint");
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 添加请求头
connection.setRequestProperty("Content-Type", "application/json");
// 启用输出流,向服务器发送数据
connection.setDoOutput(true);
// 准备请求体数据
String jsonInputString = "{\"key\":\"value\"}";
// 写入请求体数据
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(jsonInputString);
wr.flush();
wr.close();
}
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
// 读取响应内容
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("POST Response Content :: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
如果你需要使用第三方库,比如Apache HttpClient,你可以参考以下示例代码:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
public class HttpPostWithApacheHttpClient {
public static void main(String[] args) {
HttpClient httpClient = new HttpClient();
try {
// 创建PostMethod对象
PostMethod postMethod = new PostMethod("http://example.com/api/endpoint");
// 设置请求头
postMethod.setRequestHeader("Content-Type", "application/json");
// 设置请求体
postMethod.setRequestEntity(new StringRequestEntity("{\"key\":\"value\"}", "UTF-8"));
// 执行请求
int statusCode = httpClient.executeMethod(postMethod);
System.out.println("POST Response Code :: " + statusCode);
// 获取响应内容
String responseBody = postMethod.getResponseBodyAsString();
System.out.println("POST Response Content :: " + responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,上述代码示例中使用的Apache HttpClient库需要添加相应的依赖到你的项目中。如果你使用的是Maven,可以在`pom.xml`文件中添加以下依赖:
commons-httpclient commons-httpclient
3.1
请根据你的项目需求选择合适的方法,并确保处理好异常和资源释放