How to post a rest api request with Key:Value multipart/form-data using karate - multipartform-data

I want to post a request which is multipart/form-data. But it has body which is Key:value pair. It is working in Postman, soapui and parasoft soatest. Below is the code which i tried.
Given url 'http://localhost:8080/services/oauth2/token'
And multipart field username=username#usernmae
And multipart field password=secertePass
And multipart client_secret=98765432d1
And header Content-Type = 'multipart/form-data'
When method post
Then status 200
Error in karate:
com.intuit.karate.exception.KarateException: test.feature:9 - no step-definition method match found for: multipart field grant_type=password
at ✽.And multipart field grant_type=password (test.feature:9)

Not providing space before and after = can cause this, also field missed in client secret.
Have you tried,
And multipart field username = username#usernmae
And multipart field password = secertePass
And multipart field client_secret = 98765432d1

Related

dropbox-api get_thumbnail_v2 & get_thumbnail returns question marks(?) inside rhombs ()

I am trying to use DropBox API to get a thumbnail from DropBox and show them on Lightning Web Component in Salesforce, but can not do it because in a response Apex receiving body with black rhombs and question marks inside.
I use standard HTTP method to call
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer sl.validToken');
req.setHeader('Dropbox-API-Arg', '{"resource": {".tag": "path","path": "/folderName/pictureName.jpg"},"format": "jpeg","size": "w64h64","mode": "strict"}');
req.setHeader('Content-Type', 'text/plain; charset=utf-8');
req.setEndpoint('https://content.dropboxapi.com/2/files/get_thumbnail_v2');
req.setMethod('POST');
Http httpreq = new Http();
HttpResponse res = httpreq.send(req);
this is what I receive in body of response in Apex. The same response I have in Postman.
https://i.stack.imgur.com/90yjI.png
This is what I have in DropBox explorer with same values and headers (JSON)
https://i.stack.imgur.com/ytDxv.png
File scope is Read to everyone. SF Remote Site Settings & CSP Trusted Sites are set.
Short update:
I`ve been able to get JSON From header. I did use that piece of code:
List<String> headers = new List<String>(res.getHeaderKeys());
for(String key : headers){
System.debug('key ->>> '+key+' = '+res.getHeader(key));
}
String jsonString = res.getHeader('Dropbox-Api-Result');
System.debug('->>>ddd '+jsonString);
But still do not understand how to use it as a thumbnail in LWC.
Thank you in advance for your help.
The /2/files/get_thumbnail_v2 Dropbox API endpoint is a "content-download" style endpoint, meaning the "response body contains file content, so the result will appear as JSON in the Dropbox-API-Result response header". So, the illegible value you're receiving is the actual bytes of the thumbnail data itself. You're currently attempting to display it as text, but you'll instead need to save and display it as an image to see the thumbnail. Refer to your platform's documentation for information on how to display an image.
For reference, the Dropbox API v2 Explorer is built with knowledge of the different endpoint formats, so in this case it displays the metadata from the Dropbox-API-Result response header, and just offers the file data, in this case the thumbnail data, as a download via a "Download" button.

POST multipart/form-data with NodeRed HTTP request

I'm trying to generate a HTTP Webrequest in NodeRed that will upload a file to a website via a normal upload form. I guess i knwo how to upload a file, but i do not know how to pass the other input fieds i have to fill also.
I only found how to set http headers:
msg.headers["content-type"] = "multipart/form-data";
This is what i have so far:
I have also tried in "the missing part" to write the FormData and send the Request manually. (https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects)
But also no luck with that. Only received an Error that FormData is unknown...
In the function node, before sending msg, set request header like this
msg.headers = {
"content-type":"application/x-www-form-urlencoded"
}

libcurl imaps doesn't returns Header Field "Content-Transfer-Encoding" or "Content-Type"

I have been trying to detect encoding of an email manually, to see whether the email that i have just fetched needed to be base64 decoded or not, but that wasn't a complete solution.
So now I'm trying to download the headers (fields) of an email first, check them what kind of email it is and then proceed to decoding it with base64 in case the header says that it is a base64 encoded email or just skip it if it is a plain text or HTML text.
The problem is that the libcurl commands for fetching these fields doesn't really work, most of the time the "Content-Type" returns just an empty string or says that it is a multipart/alternative but when i check the email manually it is just a plain text which obviously doesn't need to be decoded.??
"Content-Type" field multipart/alternative usually have different parts like text, html, base64 encoded text, attachments etc.
In cases of multipart/alternative the "Content-Transfer-Encoding" field doesn't return anything at all, and this is the most important header field for me to know what it contains.
My imaps request to Gmail account looks like this:
curl_easy_setopt(curl, CURLOPT_URL,"imaps://imap.gmail.com:993/INBOX;UID=33;SECTION=HEADER.FIELDS%%20(Content-Transfer-Encoding%%20Subject%%20From%%20Content-Type)");
Which returns this:
Subject: my subject
From: myname
Content-Type: multipart/alternative; boundary="001a114930a049c6da05dskdls9"
As you can see it doesn't returns the "Content-Transfer-Encoding" field.
This email actually contains the word "Yup" only, so it is a plain text and no attachments, when checked by clicking on the "show original" message in browser.
Sys info:
Linux, C , libcurl, gmail

POST json request to Solr with cursorMark in request

Is it possible to include cursorMark value in POST request's body instead of sending it as query string parameter?
The following query:
{"query":"val:abc","limit":10,"cursorMark":"*","sort":"id asc"}
returns an error with the message: "Unknown top-level key in JSON request : cursorMark"
According to Solr Json Request API documentation, every query string parameter has a corresponding POST request parameter in JSON API, e.g. q -> query, start -> offset, etc.
However, there is no equivalent parameter for cursorMark query string parameter.
The best solution I am aware of is changing request type from application/json to application/x-www-form-urlencoded which allows using query string parameters in POST request's body. The reason why I was using application/json was to get json response, but it turns that it is controlled by wt=json parameter.
Changed query uri to: http://localhost:8983/solr/myCore/select?wt=json
Changed POST request parameters back to query string counterparts, i.e. q, start, rows, etc.
UrlEncoded the query string.
Put the encoded query string in POST body.
Changed request content type to application/x-www-form-urlencoded.
https://solr.apache.org/guide/7_7/json-request-api.html#passing-parameters-via-json says that you can augment a JSON-based POST with non-JSON params. I got this to work in 2022 with a JSON query that includes "params": {"cursorMark": "*"}, without needing to resort to changing the request type (as suggested in the accepted answer).

Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter..?

I am trying to send a PUT request to an amazonS3 presigned URL. My request seems to be called twice even if I only have one PUT request. The first request returns 200 OK, the second one returns 400 Bad Request.
Here is my code:
var req = {
method: 'PUT',
url: presignedUrl,
headers: {
'Content-Type': 'text/csv'
},
data: <some file in base64 format>
};
$http(req).success(function(result) {
console.log('SUCCESS!');
}).error(function(error) {
console.log('FAILED!', error);
});
The 400 Bad Request error in more detail:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InvalidArgument</Code>
<Message>Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified</Message>
<ArgumentName>Authorization</ArgumentName>
<ArgumentValue>Bearer someToken</ArgumentValue>
<RequestId>someRequestId</RequestId>
<HostId>someHostId</HostId>
</Error>
What I don't understand is, why is it returning 400? and What's the workaround?
Your client is probably sending an initial request that uses an Authorization header, which is being responded with a 302. The response includes a Location header which has a Signature parameter. The problem is that the headers from the initial request are being copied into the subsequent redirect request, such that it contains both Authorization and Signature. If you remove the Authorization from the subsequent request you should be good.
This happened to me, but in a Java / HttpClient environment. I can provide details of the solution in Java, but unfortunately not for AngularJS.
For the Googlers, if you're sending a signed (signature v4) S3 request via Cloudfront and "Restrict Bucket Access" is set to "Yes" in your Cloudfront Origin settings, Cloudfront will add the Authorization header to your request and you'll get this error. Since you've already signed your request, though, you should be able to turn this setting off and not sacrifice any security.
I know this may be too late to answer, but like #mlohbihler said, the cause of this error for me was the Authorization header being sent by the http interceptor I had setup in Angular.
Essentially, I had not properly filtered out the AWS S3 domain so as to avoid it automatically getting the JWT authorization header.
Also, the 400 "invalid argument" may surface as a result of wrong config/credentials for your S3::Presigner that is presigning the url to begin with. Once you get past the 400, you may encounter a 501 "not implemented" response like I did. Was able to solve it by specifying a Content-Length header (specified here as a required header). Hopefully that helps #arjuncc, it solved my postman issue when testing s3 image uploads with a presigned url.
The message says that ONLY ONE authentication allowed. It could be that You are sending one in URL as auth parameters, another - in headers as Authorization header.
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:scavenger_inc_flutter/utils/AuthUtils.dart';
import 'package:scavenger_inc_flutter/utils/URLS.dart';
class ApiClient {
static Dio dio;
static Dio getClient() {
if (dio == null) {
dio = new Dio();
dio.httpClientAdapter = new CustomHttpAdapter();
}
return dio;
}
}
class CustomHttpAdapter extends HttpClientAdapter {
DefaultHttpClientAdapter _adapter = DefaultHttpClientAdapter();
#override
void close({bool force = false}) {
_adapter.close(force: force);
}
#override
Future<ResponseBody> fetch(RequestOptions options,
Stream<List<int>> requestStream, Future<dynamic> cancelFuture) async {
String url = options.uri.toString();
if (url.contains(URLS.IP_ADDRESS) && await AuthUtils.isLoggedIn()) {
options.followRedirects = false;
options.headers.addAll({"Authorization": await AuthUtils.getJwtToken()});
}
final response = await _adapter.fetch(options, requestStream, cancelFuture);
if (response.statusCode == 302 || response.statusCode == 307) {
String redirect = (response.headers["location"][0]);
if(!redirect.contains(URLS.IP_ADDRESS)) {
options.path = redirect;
options.headers.clear();
}
return await fetch(options, requestStream, cancelFuture);
}
return response;
}
}
I disallowed following redirects.
Used the response object to check if it was redirected.
If it was 302, or 307, (HTTP Redirect Codes), I resent the request after clearing the Auth Headers.
I used an additioal check to send the headers only if the path contained my specific domain URL (or IP Address in this example).
All of the above, using a CustomHttpAdapter in Dio. Can also be used for images, by changing the ResponseType to bytes.
Let me know if this helps you!
I was using django restframework. I applied Token authentication in REST API. I use to pass token in request header (used ModHeader extension of Browser which automatically put Token in Authorization of request header) of django API till here every thing was fine.
But while making a click on Images/Files (which now shows the s3 URL). The Authorization automatically get passed. Thus the issue.
Link look similar to this.
https://.s3.amazonaws.com/media//small_image.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXXXXXXXXXXXXXXXX%2F20210317%2Fap-south-XXXXXXXXFaws4_request&X-Amz-Date=XXXXXXXXXXXXXXX&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I lock the ModHeader extension to pass Authorization Token only while making rest to REST API and not while making resquest to S3 resources. i.e. do not pass any other Authorization while making request to S3 resource.
It's a silly mistake. But in case it helps.
Flutter: if you experience this with the http dart package, then upgrade to Flutter v2.10!
Related bugs in dart issue tracker:
https://github.com/dart-lang/sdk/issues/47246
https://github.com/dart-lang/sdk/issues/45410
--> these has been fixed in dart 2.16, which has been shipped with Flutter v2.10!
https://medium.com/dartlang/dart-2-16-improved-tooling-and-platform-handling-dd87abd6bad1

Resources