java post 发送 body,使用HttpURLConnection在Request body中发送数据

I am using HttpURLConnection to make a POST request to a local service deployed in my local created using JAVA Spark.I want to send some data in request body when I make the POST call using the HttpURLConnection but every time the request body in JAVA Spark is null. Below is the code I am using for this

Java Spark POST Service Handler

post("/", (req, res) -> {

System.out.println("Request Body: " + req.body());

return "Hello!!!!";

});

HTTPClass Making the post call

`public class HTTPClassExample{

public static void main(String[] args) {

try{

URL url = new URL("http://localhost:4567/");

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

httpCon.setDoOutput(true);

httpCon.setRequestMethod("POST");

httpCon.connect();

OutputStream os = httpCon.getOutputStream();

OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

osw.write("Just Some Text");

System.out.println(httpCon.getResponseCode());

System.out.println(httpCon.getResponseMessage());

osw.flush();

osw.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}`

解决方案

You should call httpCon.connect(); only after you write your parameters in the body and not before. Your code should look like this:

URL url = new URL("http://localhost:4567/");

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

httpCon.setDoOutput(true);

httpCon.setRequestMethod("POST");

OutputStream os = httpCon.getOutputStream();

OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

osw.write("Just Some Text");

osw.flush();

osw.close();

os.close(); //don't forget to close the OutputStream

httpCon.connect();

//read the inputstream and print it

String result;

BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

ByteArrayOutputStream buf = new ByteArrayOutputStream();

int result2 = bis.read();

while(result2 != -1) {

buf.write((byte) result2);

result2 = bis.read();

}

result = buf.toString();

System.out.println(result);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值