在Java中发送HTTP POST请求,可以使用Java的内置库java.net.HttpURLConnection或者使用第三方库如Apache HttpClient。
使用java.net.HttpURLConnection发送HTTP POST请求的示例代码如下:
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api";
String data = "key1=value1&key2=value2";
URL objUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) objUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(data.getBytes(StandardCharsets.UTF_8).length));
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
connection.disconnect();
}
}
使用Apache HttpClient发送HTTP POST请求的示例代码如下:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api";
String data = "key1=value1&key2=value2";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
StringEntity stringEntity = new StringEntity(data);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
System.out.println("Response: " + responseString);
response.close();
httpClient.close();
}
}
这两个示例代码都可以发送HTTP POST请求,并且可以根据需要修改请求头、请求体等信息。
领取专属 10元无门槛券
手把手带您无忧上云