日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

nodejs 获取post数据

發(fā)布時(shí)間:2025/3/21 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 nodejs 获取post数据 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

nodejs ?獲取post數(shù)據(jù)

demo的原理:使用java向nodejs發(fā)送post請(qǐng)求,并攜帶數(shù)據(jù),nodejs收到請(qǐng)求,并將數(shù)據(jù)打印出來

nodejs服務(wù)器端代碼:

var http = require("http");
var url = require("url");
var querystring = require('querystring');?


http.createServer(function(request, response) {
? //request.setEncoding('utf8');
? response.writeHead(200, {"Content-Type": "text/plain"});
? response.write("送一段數(shù)據(jù)給你!");
? request.addListener('data', function(chunk){?
console.log('獲取的post數(shù)據(jù)為:' + chunk);
var name = querystring.parse(chunk + '').name; ?//chunk是一個(gè)對(duì)象 加上空字符串將其轉(zhuǎn)換為字符串格式
console.log("--------------------");
console.log(name);
? ? ?})
? response.end();
}).listen(8888)


java端發(fā)送post請(qǐng)求代碼:

public class NodejsPostData {
public static void main(String[] args) {
URL url;
HttpURLConnection con = null;
try {
url = new URL("http://localhost:8888/");
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
? // http正文內(nèi),因此需要設(shè)為true
con.setDoOutput(true);
? // Read from the connection. Default is true.
? ?con.setDoInput(true);
? // Post 請(qǐng)求不能使用緩存
? ? ? con.setUseCaches(false);
? ? ? // 進(jìn)行編碼
? ? ? ?con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
? con.connect();
??
? OutputStream out = new BufferedOutputStream(con.getOutputStream());
? String content = "你好,這是一個(gè)post請(qǐng)求的程序!";
? Writer writer = new OutputStreamWriter(out,"UTF-8");
? writer.write("name=javaPost");?
? writer.flush();
? writer.close(); ? //注意:如果既要使用輸入流讀取URLConnection響應(yīng)的內(nèi)容,也要使用輸出流發(fā)送請(qǐng)求參數(shù),一定要先使用輸出流,再使用輸入流。
? InputStream in = con.getInputStream(); ??
? byte[] by = new byte[128];
? String str = "";
? int len = 0;
? while((len = in.read(by))!= -1){
? //str = str + new String(by, 0, len); ?注意編碼問題,否則將會(huì)打印出亂碼
? str = str + new String(by, 0, len,"utf-8");
? }
? System.out.println(str);
? in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


執(zhí)行結(jié)果:



? ? ? ? ? ? ? ?java端console打印結(jié)果:



參考地址:http://www.java3z.com/cwbwebhome/article/article8/81193.html


《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的nodejs 获取post数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。