nodejs 获取post数据
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
總結(jié)
以上是生活随笔為你收集整理的nodejs 获取post数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nodejs 获取get中携带的参数值
- 下一篇: Photoshop自由变换图形大小