简体   繁体   English

使用HttpURLConnection发送帖子

[英]Sending post using HttpURLConnection

I have a node.js which waits for post with 2 parameters (name and pass): 我有一个node.js,它等待带有2个参数(名称和传递)的发布:

app.post('/login.html', function (req, res) {

    log.info(req.body);
    userName = req.body.name;
    pass = req.body.pass;
    ...
}

I'm trying to send post with the 2 parameters via simple java application, but I can't see that it arrive to the node.js. 我正在尝试通过简单的Java应用程序发送带有2个参数的帖子,但是我看不到它到达了node.js。

what am I missing ? 我想念什么?

The java code: Java代码:

public static void main(String[] args) {
    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://83.63.118.111:31011/login.html");

        urlConnection = (HttpURLConnection) url.openConnection();               
        urlConnection.setReadTimeout(10000);
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        urlConnection.setConnectTimeout(10000);
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        OutputStream os = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));          
        String str = "name='root'&pass='123456'";
        //System.out.print(str);
        writer.write(str);
        writer.flush();
        Thread.sleep(100);
        writer.close();
        os.close();       
}           

Your code will close when start send data (send and stop) 开始发送数据(发送和停止)时,您的代码将关闭

You should wait it done. 您应该等待它完成。

Add code after writer.flush(); writer.flush();之后添加代码writer.flush();

Example get response : 示例获取response

BufferedReader in = new BufferedReader(
        new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

or just get responseCode : 或者只是获取responseCode

int responseCode = urlConnection.getResponseCode();

Your program wait send request success or fail. 您的程序等待发送请求成功或失败。

I think you use Thread.sleep(100); 我认为您使用Thread.sleep(100); to wait send request, but it stop your Thread (don't send data to server) 等待发送请求,但会停止您的线程(不要将数据发送到服务器)

Your code have req.body , Express.js don't have it, need use middleware body-parser . 您的代码有req.body ,Express.js没有,需要使用中间件body-parser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM