使用c#从REST API获取JSON内容(有工作的javascript示例) [英] Get JSON content from REST API using c# (have working javascript example)
问题描述
Hello Everybody,
在过去的几个小时里,我一直在尝试从需要用户名和密码的其他https api接收一个简单的JSON对象。
该公司在Javasccript中提供了一个如何获取信息的工作示例。我不知道javascript,只有c#,但我似乎无法使它工作。可能是因为我不熟悉wen http请求等。
这是正常工作的JS代码:
function signin(){
username = $('#inputUsername')。val();
pass = $('#inputPassword')。val();
if(pass.length> 0&& username.length> 0){
//构建帖子请求
$ .post(source +" / login",{ username:username,password:pass},function(data,textStatus,jqxhr){
$(" header div h4#header_username")。html(username);
token = data.auth;
$('#main-content')。show()
$('#form-signin')。hide()
populateVehicles();
});
}
}
有人可以帮我转换成c#吗?我一直在尝试使用HttpClient或HttpRequest,每次收到401 Unauthorized Error或Bad Request Error。
提前致谢。
找到解决方案。发送凭据只能像这样工作。希望它有所帮助。
var data = new NameValueCollection();
data [" username"] =" USERNAME" ;;
data [" password"] =" PASSWORD" ;;
var response = wb.UploadValues(" URL"," POST",data);
到目前为止你有什么?您需要(我猜)基本的Web凭据,例如
using(WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(" username"," password");
// ..
}
Hello Everybody,
For the last few hours I've been trying to receive a simple JSON object from a rest https api that requires username and password.
The company provided a working example in Javasccript how to get the info. I don't know javascript, only c#, but I can't seem to make it work. Probably because I'm not familiar with wen http requests etc.
This is the working JS code:
function signin(){ username = $('#inputUsername').val(); pass = $('#inputPassword').val(); if(pass.length > 0 && username.length > 0){ //Build post request $.post( source+"/login", {username: username, password:pass}, function( data, textStatus, jqxhr ) { $("header div h4#header_username").html(username); token = data.auth; $('#main-content').show() $('#form-signin').hide() populateVehicles(); }); } }
Could anyone help me convert it to c#? I've been trying to use HttpClient or HttpRequest and each time I receive a 401 Unauthorized Error or Bad Request Error.
Thanks in advance.
Found the solution. Sending the credentials worked only like this. Hope it helps.
var data = new NameValueCollection(); data["username"] = "USERNAME"; data["password"] = "PASSWORD"; var response = wb.UploadValues("URL", "POST", data);
What have you so far? You need (I guess) basic web credentials, something like
using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential("username", "password"); //.. }
这篇关于使用c#从REST API获取JSON内容(有工作的javascript示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!