How to send dictionary with array using JSON? - arrays

My fellow co-worker backend programmer said that he has configure an API that expect to receive something like this from my mobile app:
[{"id":50},{"id":60}]
I'm using Alamofire which receive param dictionary to be sent. But I believe this is also the same mechanism using NSURLSession or any other third party plugins.
The question is: how should I construct the dictionary to send an array of ids, like how a HTTP form can have several text field with the same id, and then it will be received on the server end as an array of id? What I've tried so far and all fails:
param.setValue(50, forKey:"id");
param.setValue(60, forKey:"id");
// this only send the last single value
param.setValue([50, 60], forKey:"id");
// this results in error (415 unsupported media type)
param.setValue(50, forKey:"id[0]");
param.setValue(60, forKey:"id[1]");
// this also results in error (415 unsupported media type)
How can I send this correctly just like how web form send? Thanks.

I think keyword for your question is "Alamofire send json"
If your server accepts json data, you can do like this:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = [["id":50],["id":60]]
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
}
Good luck!

The problem with the first method is you're overwriting the value for the key id, that's the reason why it only sends the last value. Try sending the params as an array.
let dict = NSMutableArray()
param.setValue(50, forKey:"id")
dict.addObject(param)
param.setValue(60, forKey:"id")
dict.addObject(param)
Pass the dict as the parameter for the request method.

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.

Trying to retrieve first string from PubNub history Response

I know that the response from the pubnub history() is:
[["message","Message","message"],"Start Time Token", "End Time Token"]
im creating an string to receive the response:
String msg = response.toString();
And this should give me the full array, but now to retrieve the first message im doing this:
String[] msgOne = msg[0];
And this is not working.
for pubnub history method , the response is a org.json.JSONArray so to get the messages array you can use something like this.
JSONArray messages = (JSONArray)( ((JSONArray)response).get(0));
JSONArray class here http://www.json.org/javadoc/ provides more info about the methods that you can use on messages variable.

Getting more data from messages.get in C#

I'm having trouble getting more than just the snippet for text data for the message I am trying to retrieve using the Gmail API. Here is the piece of test code I am working with:
public string GetMail()
{
GmailService service = (GmailService)HttpContext.Current.Session["service"];
Message messageFeed = service.Users.Messages.List("me").Execute().Messages.First();
UsersResource.MessagesResource.GetRequest getReq = new UsersResource.MessagesResource.GetRequest(service, "me", messageFeed.Id);
getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
Message message = getReq.Execute();
return message.Raw;
}
For some reason, when I call message.Raw, it is returning null. I am able to retrieve other properties as what the format=minimal setting would based off of the API playground example I was playing with.
However in my code, I am setting the format enum to "full", yet I am still unable to retrieve the full data of the message.
Am I completely missing something here?
Seems like you're mixing up formats and response types. If you want the raw message as a string in Message.raw then you need to set:
getReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
If you want the parsed message back (in the "payload" field) then you can use getReq.Format of Full like you have.
Acceptable values are:
"full": Returns the parsed email message content in the payload field and the raw field is not used. (default)
"minimal": Only returns email message metadata such as identifiers and labels, it does not return the email headers, body, or payload.
"raw": Returns the entire email message content in the raw field as a string and the payload field is not used. This includes the identifiers, labels, metadata, MIME structure, and small body parts (typically less than 2KB).
from: https://developers.google.com/gmail/api/v1/reference/users/messages/get

PUT/GET with Payload using Restangular

I am using Restangular in one of my works
The server guys have give me the following calls which i need to integrate on the AngularJS client
PUT api/partners/password – RequestPayload[{password,confirmpassword}]
partner id is being sent in the header
GET api/partners/password/forgot/ - Request Payload [{emailaddress}]
partner id is being sent in the header
The javascript code that I have written to call these services is as follow
Restangular.all('Partners').one('Password').put(params); - sends params as query string
Restangular.all('Partners').one('Password').one('Forgot').get(params); - sends object in the url
I have tried other ways but it simply doesn't make the correct call.
Help me out guys!
So, for point #1. it puts the object at hand, not another object. So you have 2 options:
Option 1
var passReq = Restangular.all('Partners').one('Password');
passReq.confirmPassword = ....
passReq.put(); // confirmPassword and the params of the object will be sent
Option 2 is
var passReq = Restangular.all('Partners').one('Password').customPUT(obj);
For Point #2, you cannot send a request body (payload) in the GET unfortunately.

quoted format json from Solrj

It looks like the QueryResponse from Solrj has no mean to give you a quoted Json string with wt=on or not. All I received is something like this
{responseHeader={status=0,QTime=2,params= {fl=id,productName,imageFront,priceEng,priceEngExp...
Question:
1) Am I missing something here ? Or there is no way to get the json response properly from the Solr server by Solrj.
2) Now on my client, if I convert the non-quoted json string from Solrj, does it mean it was done two times, once in server time and one in the Solrj client time ?
You can get JSON response by setting wt=json to the Solr query. Example URL is shown below :
localhost:8983/solr/select/?q=:&rows=10&indent=on&wt=json
You can't get JSON response using Solrj. You don't need to use Solrj for this purpose.By sending HTTP requests to the URL above, you can get json response.
With newer versions of Solr (starting with 4.7.0) it is possible to return the query response directly in json-format. This can be done with the NoOpResponseParser.
SolrQuery query = new SolrQuery();
QueryRequest req = new QueryRequest(query);
NoOpResponseParser rawJsonResponseParser = new NoOpResponseParser();
rawJsonResponseParser.setWriterType("json");
req.setResponseParser(rawJsonResponseParser);
NamedList<Object> resp = mySolrClient.request(req);
String jsonResponse = (String) resp.get("response");
System.out.println(jsonResponse );

Resources