如何使用HttpURLConnection在请求正文中发送数据? [英] How do you send data in a Request body using HttpURLConnection?

查看:217
本文介绍了如何使用HttpURLConnection在请求正文中发送数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HttpURLConnection向本地部署并使用JAVA Spark创建的本地服务发出POST请求. 当我使用HttpURLConnection进行POST调用时,我想在请求正文中发送一些数据,但是每次JAVA Spark中的请求正文为空时.下面是我正在为此使用的代码

Java Spark POST服务处理程序

I am using HttpURLConnection to make a POST request to a local service deployed locally and 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

post("/", (req, res) -> {
    System.out.println("Request Body: " + req.body());
    return "Hello!!!!";
});

HTTPClass进行POST调用

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();
        }
    }
}

推荐答案

仅在将参数写入主体后才可以调用httpCon.connect();,而不是在此之前.您的代码应如下所示:

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(httpCon.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);

这篇关于如何使用HttpURLConnection在请求正文中发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆