码迷,mamicode.com
首页 > Windows程序 > 详细

通过HttpClient实现跟Nodejs API接口的数据交互

时间:2015-07-11 01:03:10      阅读:609      评论:0      收藏:0      [点我收藏+]

标签:

一个简单的例子,通过HttpClient post数据来实现登陆nodejs的服务接口

  • nodejs: 使用expressjs + body-parser开发一个简单的login登陆服务接口

        

var express = require(‘express‘),
    bodyparser = require(‘body-parser‘);

var app = express();
app.use(bodyparser.json({limit:‘1mb‘}));
app.use(bodyparser.urlencoded({extended:true , limit:‘1mb‘}));

//登陆接口> http://127.0.0.1:3000/login
app.post(‘/login‘ , function(req,res){
    var username = req.body.username;
    var password = req.body.password;
    console.log(‘username:‘+ username +"; password:"+password);
    res.json({"message":‘welcome to login‘, ‘status‘:19999});
});

app.listen(3000, function(){
	console.log(‘server is running‘);
});

  

  • 新建一个WPF工程,在主窗体添加一个button按钮,然后编写button的click事件

  

private void _btnpost_Click_1(object sender, RoutedEventArgs e)
{
    HttpClient client = new HttpClient();
    var postdata  = new List< KeyValuePair< string ,string >>();
    postdata.Add(new KeyValuePair<string,string>("username","vison"));
    postdata.Add(new KeyValuePair<string,string>("password","vison1987"));
    HttpContent content = new FormUrlEncodedContent( postdata);
    client.PostAsync("http://127.0.0.1:3000/login",content).ContinueWith( (posttask) =>{
      posttask.Result.Content.ReadAsStringAsync().ContinueWith((result) =>
        {
            MessageBox.Show(result.Result.ToString()); //=>s输出json格式字符串{"message":‘welcome to login‘, ‘status‘:19999}
        }); posttask.Result.EnsureSuccessStatusCode(); 
      });     
}

 

 =+ 测试完毕

通过HttpClient实现跟Nodejs API接口的数据交互

标签:

原文地址:http://www.cnblogs.com/visonme/p/4637764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!