I'have a simple restApi, when I call it with postMan it works but in asp.net by restsharp it return always nothing.
Why?
Dim client = New RestClient("https://testapiall1.azurewebsites.net/myapi/test/1")
client.Timeout = -1
Dim requestapi = New RestRequest(Method.GET)
requestapi.AddHeader("Content-Type", "application/json")
Dim responseapi As IRestResponse = client.Execute(requestapi)
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(responseapi.Content)
Recap: If I call Rest API with https not working.
Dim client = New RestClient("https://testapiall1.azurewebsites.net/myapi/test/1")
Only Http works
Dim client = New RestClient("http://testapiall1.azurewebsites.net/myapi/test/1")
The RestApi is on the MS Azure everybody can access, please someone can write some code for .Net that works?
First of all, your "API" doesn't return a valid JSON. It returns a string "value", which is not JSON.
Second, you try to deserialize to type object, which is not something you can do. You must deserialize to a specific type.
With RestSharp 107 you can do:
Dim client = New RestClient("https://testapiall1.azurewebsites.net/myapi/test/1")
Dim request = New RestRequest(Method.Get)
Dim response = Await client.ExecuteAsync(requestapi)
The response.Content will then be value.
Related
I am sending JSON data to external API as following :
Dim url = "https://********"
Dim _httpClient = New HttpClient()
_httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("MyUsername", "MyPassword")
Using content = New StringContent(json, System.Text.Encoding.UTF8, "application/json")
Dim result As HttpResponseMessage = _httpClient.PostAsync(url, content).Result
If result.StatusCode = System.Net.HttpStatusCode.Created Then
Console.WriteLine(result.StatusCode)
Return True
End If
but I am receiving the following error:
{"status":400,"message":"Invalid Request","data":[{"field":"username","message":"Username required"},{"field":"password","message":"Password required"}]}
how to fix this issue ?
As per your API definition it is expecting username and password in the header as key value pair. you can add them like this.
_httpClient.DefaultRequestHeaders.Add("Username", "MyUsername");
_httpClient.DefaultRequestHeaders.Add("password", "MyPassword");
I am doing crud operation(Using Stored Procedure) in wcf restful service .I have done with creating services,but How do I consume that service in my plain ASP.net Application(without Javascript,Jquery,AJAX). As I am new in WCF rest service.Plz give me step by step operation.
string sURL = #"http://localhost:50353/urUriName/"+ txtfname.Text;
WebRequest webGETURL;
webGETURL = WebRequest.Create(sURL);
webGETURL.Method = "DELETE";
webGETURL.ContentType = #"Application/Json; charset=utf-8";
HttpWebResponse wr = webGETURL.GetResponse() as HttpWebResponse;
Encoding enc=Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(wr.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
wr.Close();
// assign the final result to text box
Response.Write(strResult);
I have a webservice which i need to call in .net application. The link looks like this.
http://www.contoso.com/student?id=12345
This will work only when its called like this. For rest of the this i dont have access. ie if i call it on a browser without the querystring it will not work. but with querystring it will return an XML data.
Now, when i call this in the .net application its not working?
How can I call this in a .NET application?
The Normal Webservice Importing methods are not working since it needs a querystring with value and we dont have access to the links which doesnt have the querystring.
How are you currently trying to download it?
A very simple way to do this is to use the HttpWebRequest and HttpWebResponse classes;
public XmlDocument GetStudentXml(int studentId)
{
XmlDocument targetXml = new XmlDocument();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://www.contoso.com/student?id={0}", studentId));
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (Stream responseStream = webResponse.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(responseStream);
targetXml.Load(reader);
reader.Close();
}
webResponse.Close();
return targetXml;
}
This method simply creates a HttpWebRequest, initializes it with the URL (via String.Format so as to append the student id), some windows credentials and the expected content type.
It then calls the remote address via the GetResponse method. The response is then loaded into a stream, and an XmlTextReader is used to load the Xml data from the response stream into the XmlDocument, which is then returned to the caller.
You can also use WebClient and XDocument to achieve the same thing:
string url = String.Format("http://www.contoso.com/student?id={0}", studentId);
string remoteXml;
using (var webClient = new WebClient())
{
remoteXml = webClient.DownloadString(url);
}
XDocument doc = XDocument.Parse(remoteXml);
I am having a problem in passing parameters to webservice which except POST data in JSON. I am using HttpWebRequest for this, following is the code i have tried so far, but everytime server returns any of these two errors:
Error 1:
{"command":null,"handle":null,"code":2003,"msg":"Required parameter missing","error":["Parameter 'login_handle' missing.","Parameter 'login_pass' missing."],"params":{"0":{"Key":"login_handle","Value":"test"},"1":{"Key":"login_pass","Value":"test"},"handle":"example.com"},"svTRID":null,"response":[]}
Error 2:
{"command":null,"handle":null,"code":2400,"msg":"Command failed","error":["Internal Server Error. resulted in the following error: array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":[],"svTRID":null,"response":[],"children":[{"command":"Internal Server Error.","handle":null,"code":2400,"msg":"Command failed","error":["array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":{"errno":2,"errstr":"array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object","errfile":"\/home\/ote\/httpapi\/v1\/index.php","errline":54},"svTRID":null,"response":[]}]}
Here is the code:
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
Dictionary<string, string> data = new Dictionary<string, string>();
data["login_handle"] = "test";
data["login_pass"] = "test";
System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
webReq.Method = "POST";
webReq.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
writer.Write(json);
writer.Close();
System.Net.WebResponse webResp = webReq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string s = sr.ReadToEnd().Trim();
}
catch (Exception ex)
{
string e = ex.Message;
}
If i use string data = "[login_handle:'username',login_pass:'password']"; instead of Dictionary<string, string> , i receive error number 2.
Never mind, i solved it myself, instead of using Dictionary type i used anonymous type like this var data = new { login_handle = "test", login_pass = "test" }; and it solved my problem.
What you should have done is create a DataContract class (we'll call JsonData) which has two DataMembers named login_handle and login_pass.
Then, in the DataContractJsonSerializer, pass typeof(JsonData) to the constructor.
This solution is the best because you cannot create complex types using an anonymous type. Also, by parenting your DataContracts you can easily create complex JSON.
I am looking for an application that can do the following
a) Programmatically auto login to a page(login.asxp) using HttpWebResponse by using already specified username and password.
b) Detect the redirect URL if the login is successful.
c) Submit another form (settings.aspx) to update certain fields in the database.
The required coding needs to be using asp.net
The application needs to complete this entire process in the same session cookie.
string sUrl = "login.aspx";
HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(sUrl);
CookieContainer oMyCookies = new CookieContainer();
oRequest.CookieContainer = oMyCookies;
// encode postdata into byte array. the postdata string format will most likely be different and you'll have to examine the postdata going back and forth using some firefox addon like LiveHTTPHeaders
byte[] oPostData = System.Encoding.UTF8.GetBytes("username=" + HttpUtility.UrlEncode(sUser) + "&pass=" HttpUtility.UrlEncode(sPass));
using (Stream oStream = oRequest.GetRequestStream())
{
oStream.Write(oPostData, 0, oPostData.Length);
}
HttpWebResponse oResponse = oRequest.GetResponse();
// save response cookies in our cookie object for future sessions!
foreach (Cookie oCookie in oResponse.Cookies)
{
oMyCookies.SetCookies(sUrl, oCookie.ToString());
}
// maybe check response headers for location
string sResponseContents = null;
using (StreamReader oReader = new StreamReader(oResponse.GetResponseStream())
{
// store server response into string
sResponseContents = oReader.ReadToEnd();
}
...this is the basic code required for what you want to do.