Using RestSharp I ever see "{\"message\": \"TypeError: sign() takes at least 2 arguments (0 given)\", \"exception\": \"TypeError\"}" - api

I using RestSharp (v 107.3.0.0) to post data on a Web API, when I using postman to test te post is ok, bu when I using RestSharp ever I receive:
"{"message": "TypeError: sign() takes at least 2 arguments (0 given)", "exception": "TypeError"}"
Resumin my code:
var client = new RestClient(http://192.168.2.59);
var request = new RestRequest("api/sign", Method.Post);
/*
here I set some AddParameter, but using parameter or not I ever seen the same error. For that reason I will not put these parementer and too proteted some sensitive proyect information.
*/
RestResponse response = await client.PostAsync(request);
The error will to be clear, but sing is not a method, is a resource.

Related

How to acquire the response body from Apache HttpClient5's HttpResponse?

Getting the status code and response body was this easy in version 4:
StringEntity entity = new StringEntity(jsonData.toString());
HttpResponse r = org.apache.http.client.fluent.Request.Post(uri)
.connectTimeout(10*1000)
.socketTimeout(10*1000)
.addHeader("Content-Type", "application/json; charset=utf-8")
.body(entity)
.execute()
.returnResponse();
int status = r.getStatusLine().getStatusCode();
String body = EntityUtils.toString(r.getEntity(), "UTF-8");
return new CoolResponse(status, body);
But now in httpclient5 for some reason it isn't possible to get anything relating to the response body from an HttpResponse. Very confused by this. If I follow example 3 in their quickstart (https://hc.apache.org/httpcomponents-client-5.0.x/quickstart.html) it proposes I create an CloseableHttpClient, an HttpGet and a CloseableHttpResponse, but none of those allow you to set a connection timeout. Trying to find the best of both worlds but the options seem kind of scrambled here.
It's not mentioned in the quickstart, but in the fluent API you can follow up execute() with handleResponse() and pass it a lambda.
I wound up finding a much better article than the quickstart here:
https://ok2c.github.io/httpclient-migration-guide/migration-to-classic.html
Edit: that link is down, there is now an equivalent guide on apache's site
https://hc.apache.org/httpcomponents-client-5.2.x/migration-guide/migration-to-classic.html

How to Emulate a POST Request from PostMan - For a series of Integration Tests in a WebAPI Development

I am using PostMan as part of the testing regime for a WebAPI service development that I am working on. In order for external parties to gain access to our WebAPI service they first need to obtain an access token.
The POST request returns some JSON containing the required access token:
{
"access_token": "anencryptedaccesstoken",
"scope": "am_application_scope default",
"token_type": "Bearer",
"expires_in": 3218
}
I am putting together a series of integration tests which need to emulate the POST calls from POSTMAN. I am currently using System.Net.WebClient to achieve this. I am not sure what I need to do in order to achieve my goal. Here is a function that I am using to try and obtain the access token:
Public Shared Function GetAccessToken(ByVal endpoint As String, wc As WebClient) As String
Dim result As String = ""
Dim data As Byte() = Nothing
'Header information
wc.Headers.Add("Authorization", "Basic <alongencryptedstring>")
wc.Headers.Add("Content_Type", "application/x-www-form-urlencoded")
result = wc.UploadString(endpoint, "POST", "")
Return result
End Function
The 'Body' tab in PostMan contains the following entries:
grant_type - client_credentials
Content_Type - application%2Fx-www-form-urlencoded
In this instance as far as I am aware there is no 'data' element to the PostMan request hence the empty string in my use of UploadString. The function returns the following error:
"The remote server returned an error: (415) Unsupported Media Type."
I am new to web app development so please bear with me, I am finding it difficult to phrase what I think are meaningful question in the context of this post, I hope however that I have ssupplied sufficient information to convey the gist of my problem and for someone to be able to respond appropriately.
Kind Regards
Paul.

Append URL Query Strings to request

I'm trying to send a POST request and format the query string in a specific format. Order doesn't matter aside from the first parameter, but I haven't been successful.
What I need:
localhost/someapp/api/dosomething/5335?save=false&userid=66462
What some of my attempts have spit out:
http://localhost/someapp/api/dosomething/?Id=29455&save=false&userId=797979
http://localhost/someapp/api/dosomething/?save=false&userId=797979
How I formatted the request:
request.AddQueryParameter("Id", "29455");
request.AddQueryParameter("save", "false");
request.AddQueryParameter("user", "4563533245");
If I try AddParameterfor Id it doesn't get appended on the query string (I'm thinking because it's a POST and not a GET), so that won't work. The API isn't expecting a form, it's expecting :
(string id, List<Dictionary<string,string>>)
I could use a StringBuilder, but that feels wrong. I'm not sure if UrlSegment is the best way to go either, since I would basically be hacking the query string. Is there a way to format my request in the format I need using RestSharp's API?
What I ended up using is UrlSegment and then kept the .AddQueryParameter methods, so the final code block looks like :
var url = new RestClient(localhost/someapp/api/dosomething/{id});
var request = new RestRequest(Method.POST);
request.AddParameter("Id", "5335", ParameterType.UrlSegment);
request.AddQueryParameter("save", "true");
request.AddQueryParameter("UserId", "5355234");
Which produced the URI I needed.
The easiest coding process for using RestSharp or any other API client library would be to use Postman to generate if you are unsure of how to code it. Download Postman, do a new request, enter the URL string to send to the API, click on Code, select C# (RestSharp) from the dropdown. Here is the code it generated.
var client = new RestClient("http://localhost/someapp/api/dosomething /5335?save=false&userid=66462");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "bd05aa45-f1b9-4665-a3e7-888ad16f2800");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

Authenticate in Xero from Salesforce

I'm new to Oauth and I stack on getting oauth_access_token to work with Xero. Web Service authentication doesn't work for me.
Xero returns the following error message "oauth_problem=signature_invalid&oauth_problem_advice=Failed to validate signature".
The generated signature is incorrect, but what is right way to generate it?
Here is APEX code which generates Endpoint. What is wrong?
Http h = new Http();
String consumer_key='XXX';
Long tmp=(System.now().getTime()/1000);
Blob isItCorrect = Crypto.generateMac('HMacSHA1', Blob.valueOf('https://api.xero.com/api.xro/2.0'), Blob.valueOf(consumer_key));
String signature= EncodingUtil.urlEncode(EncodingUtil.base64Encode(isItCorrect), 'UTF-8');
// Try to get access token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.xero.com/oauth/RequestToken?oauth_consumer_key='+consumer_key+
'&oauth_signature_method=RSA-SHA1'+
'&oauth_signature='+signature+
'&oauth_timestamp='+tmp+ '&oauth_nonce='+tmp+'&oauth_version=1.0&scope=https%3A%2F%2Fapi.xero.com%2Fapi.xro%2F2.0');
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
System.debug('~~~ '+res.getBody());
It generates following Endpoint:
Endpoint=https://api.xero.com/oauth/RequestToken?oauth_consumer_key=ICSP7Y5K2TG7RIIC6Y7R7KLC1AHWYC&oauth_signature_method=RSA-SHA1&oauth_signature=gWP02y2EIatw4xilTvd5Iq3e0%2Fw%3D&oauth_timestamp=1372123781&oauth_nonce=1372123781&oauth_version=1.0&scope=https%3A%2F%2Fapi.xero.com%2Fapi.xro%2F2.0
Just as an aside: I've never worked with salesforce so I'm not sure if there's a better
way to leverage existing oauth work on the platform, it's very rare
now to have to write all the oauth signature stuff yourself and it's
easy to make a mistake but here goes]
I think your signature base string is incorrect.
As far as I can tell you're just performing HMAC-SHA1 over https://api.xero.com/api.xro/2.0
if you read the OAuth Spec here: http://oauth.net/core/1.0/#anchor14 you need to construct the following base string (based on the request above)
GET&https%3A%2F%2Fapi.xero.com%2Foauth%2Frequesttoken&oauth_consumer_key%3DCONSUMER_KEY%26oauth_nonce (etc etc, just append all your query parameters apart from oauth_consumer as url encoded key=value pairs, in alphabetical order)
and then you need to create the hash with the key CONSUMER_KEY&CONSUMER_SECRET (both CONSUMER_KEY and CONSUMER_SECRET should be parameter encoded as per the OAuth Spec)
That should give you a valid signature..
Edit: I found this library which might be of help: https://code.google.com/p/sfdc-oauth-playground/

Upload file to Solr with HttpClient and MultipartEntity

httpclient, httpmime 4.1.3
I am trying to upload a file through http to a remote server with no success.
Here's my code:
HttpPost method;
method = new HttpPost(solrUrl + "/extract");
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
MultipartEntity me = new MultipartEntity();
me.addPart("myfile", new InputStreamBody(doubleInput, contentType, fileId));
method.setEntity(me);
//method.setHeader("Content-Type", "multipart/form-data");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse hr = httpClient.execute(method);
The server is Solr.
This is to replace a working bash script that calls curl like this,
curl http://localhost:8080/solr/update/extract?literal.id=bububu&commit=true -F myfile=#bububu.doc
If I try to set "Content-Type" "multipart/form-data", the receiving part says that there's no boundary (which is true):
HTTP Status 500 - the request was rejected because no multipart boundary was found
If I omit this header setting, the server issues an error description that, as far as I discovered, indicates that the content type was not multipart [2]:
HTTP Status 400. The request sent by the client was syntactically incorrect ([doc=null] missing required field: id).
This is related to [1] but I couldn't determine the answer from it. I was wondering,
I am in the same situation but didn't understand what to do. I was hoping that the MultipartEntity would tell the HttpPost object that it is multipart, form data and have some boundary, and I wouldnt set content type by myself. I didn't quite get how to provide boundaries to the entities - the MultipartEntity doesn't have a method like setBoundary. Or, how to get that randomly generated boundary to specify it in addHeader by myself - no getBoundary methor either...
[1] Problem with setting header "Content-Type" in uploading file with HttpClient4
[2] http://lucene.472066.n3.nabble.com/Updating-the-index-with-a-csv-file-td490013.html
I am suspicious of
method.getParams().setParameter("literal.id", fileId);
method.getParams().setBooleanParameter("commit", true);
In the first line, is fileId a string or file pointer (or something else)? I hope it is a string. As for the second line, you can rather set a normal parameter.
I am trying to tackle the HTTP Status 400. I dont know much Java (or is that .Net?)
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error