用Java写数据到POST请求

               

用Java写数据到POST请求

HTTP POST请求最常见的用途是发送表单参数到服务器。除了发送表单数据,还可以使用POST的消息Body体发送各种数据(如纯文本、XML文档等)。本文讲述如何用Java将数据写入POST请求的Body体。

import java.io.IOException;import java.io.InputStream;import java.io.OutputStreamWriter;import java.net.URL;import java.net.URLConnection;import java.util.logging.Level;import java.util.logging.Logger;import org.apache.commons.io.IOUtils;public class RequestTest public static void main(String[] args){  try{   // Configure and open a connection to the site you will send the request   URL url = new URL("http://www.iana.org/domains/example/");   URLConnection urlConnection = url.openConnection();   // 设置doOutput属性为true表示将使用此urlConnection写入数据   urlConnection.setDoOutput(true);   // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型   urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");   // 得到请求的输出流对象   OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());   // 把数据写入请求的Body   out.write("message = Hello World chszs");   out.flush();   out.close();      // 从服务器读取响应   InputStream inputStream = urlConnection.getInputStream();   String encoding = urlConnection.getContentEncoding();   String body = IOUtils.toString(inputStream, encoding);   System.out.println(body);  }catch(IOException e){   Logger.getLogger(RequestTest.class.getName()).log(Level.SEVERE, null, e);  } }}

是不是很简单?


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值