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.
I have searched a lot and found no suitable answers.
I have 2 post controller method as
#PostMapping("/saveStudentInfo")
public String saveStudentInfo(#RequestBody Students stud, HttpServletRequest request) {
students.setId(stud.getId());
students.setStudentName(stud.getStudentName());
students.setSchoolInfo(stud.getSchoolInfo());
System.out.println("Hello A= "+request.getSession(false).getId());
return "Saved Sucessfully";
}
#PostMapping("/saveSubjectInfo")
public String saveSubjectInfo(#RequestBody Subjects sub, HttpServletRequest request) {
subject.setSubjectName(sub.getSubjectName());
subject.setSubjectTeacher(sub.getSubjectTeacher());
System.out.println("Hello B= "+request.getSession(false).getId());
return "Saved Sucessfully Subject";
}
Now from postman these calls, works successfully, as same JSessionId is generated
==>Problem
When called from react app via browser on 2nd
saveSubjectInfo request I get different JSessionId, as in New-Session was Created
And I have annotated both Students and Subjects as #SessionScoped.
==>Requirement
Need to maintain session, and for that JSessionId needed to be same.
By default browsers support the GET method when API is hit directly from the browser URL bar. Also the POST and PUT method are usually supposed to make request along with some data to the serving method as the body so that it is not viewed in the browser request. For POST or PUT Postman app can be used.
I am trying to call the Microsoft Graph API to create a domain. Unfortunately when I go to make the call, I receive an error stating that the "JSON Payload is empty".
Here is the call I am making:
GraphServiceClient _graphServiceClient =
new GraphServiceClient(new GraphAuthenticationHelper(NetOrgDomain));
HttpRequestMessage httpRequestMessage =
new HttpRequestMessage(httpMethod, requestUri);
string content = "{\"id\": \"sampleDomainAdd.info\"}";
var json = JsonConvert.SerializeObject(content);
var jsonContent = new StringContent(json, Encoding.UTF8, "application/json");
httpRequestMessage.Content = jsonContent;
HttpResponseMessage response =
await _graphServiceClient.HttpProvider.SendAsync(httpRequestMessage);
You've got an mix of Graph SDK and direct HTTP calls going on here. When using the Microsoft Graph .NET Client Library, you should be using the objects it provides rather than attempting to roll your own.
It also greatly simplifies your code:
var domain = await graphClient.Domains.Request().AddAsync(new Domain
{
Id = "sampleDomainAdd.info"
});
As an aside, the error you're getting currently is due to you're sending the data without the content-type being set to application/json in your HTTP request.
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
I'm attempting to insert a Contact to the Mirror API, but I keep getting a 400 Bad Request error.
My code to build the request is as follows:
Http h = new Http();
HttpRequest firstPost = new HttpRequest();
firstPost.setEndpoint('https://www.googleapis.com/mirror/v1/contacts');
firstPost.setMethod('POST');
firstPost.setHeader('Authorization', 'Bearer ' +access_token);
System.debug('Bearer '+access_token);
firstPost.setBody(postBody);
firstPost.setHeader('Content-Type', 'application/json');
The postBody is hardcoded for now as:
{
"kind":"mirror#contact",
"id":"harold",
"displayName":"Harold Penguin",
"imageUrls": ["https://developers.google.com/glass/images/harold.jpg"]
}
I've confirmed the access_token is being sent. Any ideas? Thanks!
You don't need (and should not specify) the kind attribute when doing contact.insert. This is assumed (you better be inserting a contact), and I can see how it might be causing problems if you provide it. Notice that https://developers.google.com/glass/v1/reference/contacts/insert does not list it as an attribute, and the Raw HTTP example does not show it.