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");
Related
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.
I set the DropBox application type Full DropBox; I set on my application the following function:
Private Const AppKey As String = "my key"
Private Const AppSecret As String = "my secret"
Private Function Upload() As String
Dim client As DropNetClient
Dim token As UserLogin
Dim userToken As String = My.Settings.userToken
Dim userSecret As String = My.Settings.userSecret
Dim needAccessToken As Boolean = (String.IsNullOrEmpty(userToken) Or String.IsNullOrEmpty(userSecret))
If (needAccessToken) Then
client = New DropNet.DropNetClient(AppKey, AppSecret)
client.UseSandbox = True
client.GetToken()
Dim url = client.BuildAuthorizeUrl()
Try
token = client.GetAccessToken()
Catch ex As Exception
Console.WriteLine("Exception! " + ex.Message)
Exit Function
End Try
userToken = token.Token
userSecret = token.Secret
My.Settings.Properties.Item("userToken").DefaultValue = userToken
My.Settings.Properties.Item("userSecret").DefaultValue = userSecret
My.Settings.Save()
Else
client = New DropNet.DropNetClient(AppKey, AppSecret, userToken, userSecret)
client.UseSandbox = True
End If
Dim rawData As Byte() = File.ReadAllBytes(Server.MapPath("") + "/Fax/" + "Fax.zip")
Dim result As MetaData = client.UploadFile("/", "fax.zip", rawData)
End Function
Unfortunately education tokens = GetAccessToken () I get the error:
Received Response [Unauthorized]: Expected to see [OK]. The HTTP response was [{" "error" ":" "Request token has not been properly authorized by a user. ""}] ".
I checked the URL (client.BuildAuthorizedUrl ()) and returns me "Unauthorized".
How can I link to Dropbox folder? I do something wrong? Or do I need to set better application of Dropbox?
Once you get the URL via BuildAuthorizeUrl, you need to send the user to that address and have them authorize your app. Only once they've done that can you call GetAccessToken.
The error you're seeing is because you're trying to get the access token before the user has actually authorized your app.
I'm having some problem consuming REST Service and want to figure out what I'm missing in implementation.
https://<server-name-or-address>/api/sessions
if I call this rest api using cURL, it works just fine by following script
curl -i -k -H "Accept:application/*+xml;version=1.5" -u username:password -X POST https://<server-name-or-address>/api/sessions
However, it isn't working at all with C# asp.net. I'm not sure what I'm missing here. Here are my attempts:
1) Using HTTP Web Request
Uri address = new Uri(url);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/*+xml;version=1.5";
request.Credentials = new NetworkCredential(username,password);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// following exception fires on calling aforementioned statement
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
2) Using Hammock.net
Hammock.RestClient client = new Hammock.RestClient();
string encodedAPIKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
client.AddHeader("Accept", "application/*+xml;version=1.5");
client.AddHeader("Authorization", "Basic " + username + ":" + password);
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content; // exception
3) Using RestSharp
string _loginInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
RestSharp.RestClient client = new RestSharp.RestClient();
client.AddDefaultHeader("Accept", "application/*+xml;version=1.5");
client.AddDefaultHeader("Authorization", "Basic " + _loginInfo);
client.BaseUrl = url;
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.AddUrlSegment("method", "POST");
request.AddUrlSegment("uri", url);
string result = client.Execute(request).Content;
I also have tried with HttpClient, WebRequest, WebClient though nothing appears to work.
Try manually setting the Authorization header yourself in the HTTP request.
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add("Authorization", authorization);
EDIT:
It looks as though it may be due to a self-signed, expired, or otherwise invalid cert. Try the following
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Gleaned from this SO: https://stackoverflow.com/questions/5595049/servicepointmanager-servercertificatevalidationcallback-question
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.