我有一个node.js,它等待带有2个参数(名称和传递)的帖子:
app.post('/login.html', function (req, res) {
log.info(req.body);
userName = req.body.name;
pass = req.body.pass;
...
}
我试图通过简单的Java应用程序发送带有2个参数的帖子,但我看不到它到达了node.js。
我想念什么?
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();
}
答案 0 :(得分:2)
开始发送数据(发送和停止)时,您的代码将关闭
您应该等待它完成。
在writer.flush();
之后添加代码
示例获取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();
或仅获得responseCode
:
int responseCode = urlConnection.getResponseCode();
您的程序等待发送请求成功还是失败。
我认为您使用Thread.sleep(100);
等待发送请求,但它会停止您的线程(不向服务器发送数据)
您的代码有req.body
,Express.js没有,需要使用中间件body-parser。