简体   繁体   English

Java HTTP POST 请求未发送任何内容

[英]Java HTTP POST request not sending anything

I am new to the HTTP request in java.我是 java 中的 HTTP 请求的新手。 I have been trying to send an HTTP Post request to my NODE.JS server with the parameter key:12345.我一直在尝试使用参数 key:12345 向我的 NODE.JS 服务器发送 HTTP Post 请求。 However, it doesn't send anything to my server.但是,它不会向我的服务器发送任何内容。 I tried tested my NOEDJS server to see if it worked in POSTMAN, and it did.我尝试测试我的 NOEDJS 服务器,看看它是否在 POSTMAN 中工作,并且确实如此。 So I am sure that this is something with the java that I made.所以我确信这是我制作的 java 的问题。 I think a look at my code would help.我认为看看我的代码会有所帮助。 Here it is down below.它在下面。

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ConnectionFactory {

    private double API_VERSION = 0;
    private String API = "";

    private String METHOD = "POST";
    private String USER_AGENT = "Mozilla/5.0";
    private String TYPE = "application/x-www-form-urlencoded";
    private String data = "";
    private URL connection;
    private HttpURLConnection finalConnection;

    private HashMap<String, String> fields = new HashMap<String, String>();

    public ConnectionFactory(String[] endpoint, String url, double version) {
        this.API_VERSION = version;
        this.API = url;
        fields.put("version", String.valueOf(version));
        for (int i = 0; i < endpoint.length; i++) {
            String[] points = endpoint[i].split(";");
            for (int f = 0; f < points.length; f++) {
                fields.put(points[f].split(":")[0], points[f].split(":")[1]);

            }
        }
    }

    public String buildConnection() {
        StringBuilder content = new StringBuilder();
        if (!this.getEndpoints().equalsIgnoreCase("") && !this.getEndpoints().isEmpty()) {
            String vars = "";
            String vals = "";
            try {
                for (Map.Entry<String, String> entry: fields.entrySet()) {
                    vars = entry.getKey();
                    vals = entry.getValue();
                    data += ("&" + vars + "=" + vals);

                }

                if (data.startsWith("&")) {
                    data = data.replaceFirst("&", "");

                }
                connection = new URL(API);
                BufferedReader reader = new BufferedReader(new InputStreamReader(readWithAccess(connection, data)));
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line + "\n");

                }
                reader.close();
                return content.toString();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        } else {
            return null;
        }
        return null;
    }

    private InputStream readWithAccess(URL url, String data) {
        try {
            byte[] out = data.toString().getBytes();
            finalConnection = (HttpURLConnection) url.openConnection();
            finalConnection.setRequestMethod(METHOD);
            finalConnection.setDoOutput(true);
            finalConnection.addRequestProperty("User-Agent", USER_AGENT);
            finalConnection.addRequestProperty("Content-Type", TYPE);
            finalConnection.connect();
            try {
                OutputStream os = finalConnection.getOutputStream();
                os.write(out);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
            return finalConnection.getInputStream();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    public String getApiVersion() {
        return String.valueOf(API_VERSION);
    }
    public String getEndpoints() {
        return fields.toString();
    }
    public String getEndpointValue(String key) {
        return fields.get(key);
    }
    public void setUserAgent(String userAgent) {
        this.USER_AGENT = userAgent;
    }

    public void setMethod(String method) {
        this.METHOD = method;
    }

    public void setSubmissionType(String type) {
        this.TYPE = type;
    }
}
public class example {
    public static void main(String[] args) {

        double version = 0.1;
        String url = "http://localhost:3000";

        String[] fields = {
                "key:12345"
        };

        ConnectionFactory connection = new ConnectionFactory(fields, url, version);
        connection.setUserAgent("Mozilla/5.0");
        String response = connection.buildConnection();
        System.out.println(response);
    }
}

Here is the code for my node.js server这是我的 node.js 服务器的代码

var http = require('http');
var url = require('url');
var queryString = require('querystring')
var StringDecoder = require('string_decoder').StringDecoder;
var server = http.createServer(function(req, res) {

    //parse the URL
    var parsedURL = url.parse(req.url, true);

    //get the path
    var path = parsedURL.pathname;
    var trimmedPath = path.replace(/^\/+|\/+$/g, '');

    //queryString
    var queryStringObject = parsedURL.query;
    console.log(queryStringObject);

    if (queryStringObject.key == 12345) {
        console.log("true")
        res.end("true")
    } else {
        console.log("failed")
        res.end("false")
    }
    // var query = queryStringObject.split()

});


server.listen(3000, function() {
    console.log("Listening on port 3000");
});

The is no problem with your java client您的 java 客户端没有问题

The problem is that you are sending the content of your POST request as ""application/x-www-form-urlencoded" and then in your nodeJS server you are reading it as a query string问题是您将 POST 请求的内容作为 ""application/x-www-form-urlencoded" 发送,然后在 nodeJS 服务器中将其作为查询字符串读取

Here is a correct example using ExpressJS:这是使用 ExpressJS 的正确示例:

const express = require('express')
const app = express()

app.get('/', function (req, res) {
res.send('Hello World!')
})


var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.post('/test', function(req, res) {
var key = req.body.key;

if (key==12345)
res.send(true );
else
 res.send(false);
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})

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

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