java httppost_用Java发送HTTPPOST请求

这篇博客详细介绍了如何在Java中发送POST请求,包括发送简单表单数据、JSON数据以及上传文件。通过示例代码展示了如何设置请求头、转换数据格式以及利用HttpURLConnection进行网络通信。
摘要由CSDN通过智能技术生成

在普通Java中发送POST请求很容易。从URL,我们不需要将其转换为URLConnection使用url.openConnection();..在那之后,我们需要把它转换成HttpURLConnection,这样我们就可以访问它的setRequestMethod()方法来设置我们的方法。最后,我们将通过连接发送数据。URL url = new URL("https://www.example.com/login");URLConnection con = url.openConnection();HttpURLConnection http =

(HttpURLConnection)con;http.setRequestMethod("POST"); // PUT is another valid optionhttp.setDoOutput(true);

然后,我们需要说明我们要发送的内容:

发送一个简单的表单

来自http窗体的普通帖子具有明确定义格式。我们需要将我们的输入转换成这种格式:Map arguments = new HashMap<>();arguments.put("username", "root");arguments.put("password", "sjh76HSn!");

// This is a fake password obviouslyStringJoiner sj = new StringJoiner("&");for(Map.Entry entry : arguments.entrySet())

sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="

+ URLEncoder.encode(entry.getValue(), "UTF-8"));byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);

int length = out.length;

然后,我们可以将表单内容附加到带有适当标题的http请求中,并将其发送。http.setFixedLengthStreamingMode(length);http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

http.connect();try(OutputStream os = http.getOutputStream()) {

os.write(out);}// Do something with http.getInputStream()

发送JSON

我们还可以使用java发送json,这也很容易:byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);int length = out.length;http.

setFixedLengthStreamingMode(length);http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");http.connect();

try(OutputStream os = http.getOutputStream()) {

os.write(out);}// Do something with http.getInputStream()

请记住,对于json,不同的服务器接受不同的内容类型,请参见这,这个问题。

用java POST发送文件

由于格式更复杂,发送文件可能会被认为更具有挑战性。我们还将添加对将文件作为字符串发送的支持,因为我们不希望将文件完全缓冲到内存中。

为此,我们定义了一些助手方法:private void sendFile(OutputStream out, String name, InputStream in, String fileName) {

String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8")

+ "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";

out.write(o.getBytes(StandardCharsets.UTF_8));

byte[] buffer = new byte[2048];

for (int n = 0; n >= 0; n = in.read(buffer))

out.write(buffer, 0, n);

out.write("\r\n".getBytes(StandardCharsets.UTF_8));}private void sendField(OutputStream out, String name, String field) {

String o = "Content-Disposition: form-data; name=\""

+ URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";

out.write(o.getBytes(StandardCharsets.UTF_8));

out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));

out.write("\r\n".getBytes(StandardCharsets.UTF_8));}

然后,我们可以使用这些方法创建一个多部分POST请求,如下所示:String boundary = UUID.randomUUID().toString();byte[] boundaryBytes =

("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);byte[] finishBoundaryBytes =

("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);http.setRequestProperty("Content-Type",

"multipart/form-data; charset=UTF-8; boundary=" + boundary);// Enable streaming mode with default settingshttp

.setChunkedStreamingMode(0); // Send our fields:try(OutputStream out = http.getOutputStream()) {

// Send our header (thx Algoman)

out.write(boundaryBytes);

// Send our first field

sendField(out, "username", "root");

// Send a seperator

out.write(boundaryBytes);

// Send our second field

sendField(out, "password", "toor");

// Send another seperator

out.write(boundaryBytes);

// Send our file

try(InputStream file = new FileInputStream("test.txt")) {

sendFile(out, "identification", file, "text.txt");

}

// Finish the request

out.write(finishBoundaryBytes);}// Do something with http.getInputStream()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值