1 使用 java 原生 httpurlconnection
import java.io.bufferedreader;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.url;
import java.nio.charset.standardcharsets;
public class postrequestexample {
public static void main(string[] args) {
try {
// 请求url
string url = "https://example.com/api";
// 创建连接
url obj = new url(url);
httpurlconnection con = (httpurlconnection) obj.openconnection();
// 设置请求方法
con.setrequestmethod("post");
// 设置请求头
con.setrequestproperty("content-type", "application/json");
con.setrequestproperty("accept", "application/json");
// 请求体数据
string requestbody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 启用输出流
con.setdooutput(true);
// 发送请求体
try(outputstream os = con.getoutputstream()) {
byte[] input = requestbody.getbytes(standardcharsets.utf_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responsecode = con.getresponsecode();
system.out.println("response code: " + responsecode);
// 读取响应
try(bufferedreader br = new bufferedreader(
new inputstreamreader(con.getinputstream(), standardcharsets.utf_8))) {
stringbuilder response = new stringbuilder();
string responseline;
while ((responseline = br.readline()) != null) {
response.append(responseline.trim());
}
system.out.println("response: " + response.tostring());
}
} catch (exception e) {
e.printstacktrace();
}
}
}2. 使用 apache httpclient (推荐)
首先添加 maven 依赖:
<dependency>
<groupid>org.apache.httpcomponents</groupid>
<artifactid>httpclient</artifactid>
<version>4.5.13</version>
</dependency>
代码示例:
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 httpclientpostexample {
public static void main(string[] args) {
try (closeablehttpclient httpclient = httpclients.createdefault()) {
// 创建post请求
httppost httppost = new httppost("https://example.com/api");
// 设置请求头
httppost.setheader("content-type", "application/json");
httppost.setheader("accept", "application/json");
// 设置请求体
string requestbody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
httppost.setentity(new stringentity(requestbody));
// 执行请求
try (closeablehttpresponse response = httpclient.execute(httppost)) {
// 获取响应码
int statuscode = response.getstatusline().getstatuscode();
system.out.println("response code: " + statuscode);
// 获取响应体
httpentity entity = response.getentity();
if (entity != null) {
string result = entityutils.tostring(entity);
system.out.println("response: " + result);
}
}
} catch (exception e) {
e.printstacktrace();
}
}
}3. 使用 spring resttemplate
首先添加 maven 依赖:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
<version>2.5.0</version>
</dependency>
代码示例:
import org.springframework.http.*;
import org.springframework.web.client.resttemplate;
public class resttemplatepostexample {
public static void main(string[] args) {
// 创建resttemplate实例
resttemplate resttemplate = new resttemplate();
// 请求url
string url = "https://example.com/api";
// 设置请求头
httpheaders headers = new httpheaders();
headers.setcontenttype(mediatype.application_json);
headers.setaccept(collections.singletonlist(mediatype.application_json));
// 请求体数据
string requestbody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 创建请求实体
httpentity<string> requestentity = new httpentity<>(requestbody, headers);
// 发送post请求
responseentity<string> response = resttemplate.postforentity(url, requestentity, string.class);
// 获取响应信息
system.out.println("response code: " + response.getstatuscodevalue());
system.out.println("response body: " + response.getbody());
}
}4. 使用 java 11+ 的 httpclient (java 11及以上版本)
import java.net.uri;
import java.net.http.httpclient;
import java.net.http.httprequest;
import java.net.http.httpresponse;
import java.time.duration;
public class java11httpclientexample {
public static void main(string[] args) {
// 创建httpclient
httpclient httpclient = httpclient.newbuilder()
.version(httpclient.version.http_1_1)
.connecttimeout(duration.ofseconds(10))
.build();
// 请求体
string requestbody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 创建httprequest
httprequest request = httprequest.newbuilder()
.uri(uri.create("https://example.com/api"))
.header("content-type", "application/json")
.header("accept", "application/json")
.post(httprequest.bodypublishers.ofstring(requestbody))
.build();
try {
// 发送请求
httpresponse<string> response = httpclient.send(
request, httpresponse.bodyhandlers.ofstring());
// 输出结果
system.out.println("status code: " + response.statuscode());
system.out.println("response body: " + response.body());
} catch (exception e) {
e.printstacktrace();
}
}
}注意事项
- 对于生产环境,推荐使用 apache httpclient 或 spring resttemplate
- 记得处理异常和关闭资源
- 根据实际需求设置适当的超时时间
- 对于 https 请求,可能需要配置 ssl 上下文
- 考虑使用连接池提高性能
以上方法都可以根据实际需求进行调整,例如添加认证头、处理不同的响应类型等。
以上就是使用java发送post请求的四种方式的详细内容,更多关于java发送post请求的资料请关注代码网其它相关文章!
发表评论