Dropbox API How to Set Content-Type in RestRequest - dropbox-api

Trying to call Dropbox API v2.
Dim client = New RestClient("https://api.dropboxapi.com/2/")
Dim request = New RestRequest("files/search", Method.POST)
request.AddHeader("Authorization", "Bearer " & MYTOKEN)
request.AddHeader("Content-Type", "application/json")
'request.RequestFormat = DataFormat.Json
'request.JsonSerializer.ContentType = "application/json; charset=utf-8;"
'request.AddParameter("Content-Type", "application/json")
request.AddParameter("path", "")
request.AddParameter("query", "my file")
request.AddParameter("start", "0")
request.AddParameter("max_results", "1")
request.AddParameter("mode", "filename")
Dim res = client.Execute(request)
Always return
Error in call to API function "files/search": Bad HTTP "Content-Type" header: "application/x-www-form-urlencoded". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack"
Tried the commented code lines but still the same response. Any clue?

If my guesses are right, and this is Visual Basic code using RestSharp, then I think you need something like this (apologies if it's not quite right; I don't know VB syntax):
Dim client = New RestClient("https://api.dropboxapi.com/2/")
Dim request = New RestRequest("files/search", Method.POST)
request.AddHeader("Authorization", "Bearer " & MYTOKEN)
request.RequestFormat = DataFormat.Json
request.AddBody(New With {
.path = "",
.query = "my file",
.start = 0,
.max_results = 1,
.mode = "filename"
})
Dim res = client.Execute(request)

Solved it like this. There could be better ways to do it but this works for now.
Dim client = New RestClient("https://api.dropboxapi.com/2/")
Dim request = New RestRequest("files/search", Method.POST)
request.AddHeader("Authorization", "Bearer " & MYTOKEN)
request.AddHeader("Content-Type", "application/json") '---> this line still doesn't seem to do anything
Dim json As New JObject(New JProperty("path", ""), New JProperty("query", "my file"), New JProperty("max_results", 1), New JProperty("mode", "filename"))
request.AddParameter("application/json", json, ParameterType.RequestBody)
Dim res = client.Execute(request)
Dropbox API appears to be very sensitive as for example, the object in AddParameter cannot be a json string, it must be json object. And "1" say in max_results doesn't work, it must be 1 without the quotes. A lot of trial and error but finally worked.

Related

How to call Microsoft Graph REST API with groovy-wslite

I am trying to call Microsoft Graph API on groovy script using Java libraries. However, even though partly success, I still have some serious issues using it within my current project, so I think about trying to call the the REST API using groovy-wslite.
This is my current code for getting access token:
def authorizeHost = "https://login.microsoftonline.com"
def authorizePath = "/${azureSetting.getTenantID()}/oauth2/v2.0/authorize?"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.JSON
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}
The response from the log:
AADSTS900144: The request body must contain the following parameter: 'client_id'.
How can I change the above code, so that Microsoft Graph REST API can recognize my sending content and send back the access token.
UPDATE: After trying around, I found out that the body os post method should be as below:
type "application/x-www-form-urlencoded"
urlenc client_id: azureSetting.getClientID(),
scope: "https://graph.microsoft.com/.default",
response_type: "code"
according to doc https://learn.microsoft.com/en-us/graph/auth-v2-user#token-request your request should have Content-Type: application/x-www-form-urlencoded
you are trying to send json instead
here is your code but pointing to a test httpbin.org server and it could show what exactly you are sending to server
there is a minor change: ContentType.JSON -> ContentType.URLENC
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.3', transitive=false)
import wslite.rest.*
//just for test
def azureSetting = [ getClientID:{-> "12345"} ]
def LOGGER = [info:{x-> println x}]
//redefined host and url
def authorizeHost = "HTTP://httpbin.org"
def authorizePath = "/post"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.URLENC // <-- THE ONLY CHANGE IN YOUR CODE
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}

BODY=null returned from REST call, status = 302

I am making a REST Api call in my Java application :
RestTemplate restTemplateGES = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
String url = "http://myurl/common/api/usercontext";
String authToken = "token_value";
headers.add( "Content-Type", "application/json" );
headers.add( "Authorization", "Bearer " + authToken );
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<Object> respObject = restTemplateGES.exchange(url,HttpMethod.POST,entity,Object.class);
The call returns with Status=302 and Body=null.
When I make exactly the same call from INSOMNIA I am getting a response back in the form of JSON.
Not sure what I am doing wrong.

Groovy rest client without libraries

I am using a rest client to do Post
My code is
def postRequest() {
def message = "{ \"fields\": { \"project\": { \"id\": \"001\" },\"summary\": \"Test Issue For Jira Integration\",\"description\": \"Creating of an issue for for projects and issue types using the REST API\", \"issuetype\": { \"id\": \"5\" } }}"
// POST
def post = new URL("https://jira/rest/api/latest/issue").openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
post.setRequestProperty ("Authorization", basicAuth);
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(201)) {
println(post.getInputStream().getText());
}else
{
println(post.getInputStream().getText());
print(postRC)
}
}
I am getting 400 error code , where its getting wrong
I am successfully able to do the get request with URL
400 = bad request.
it means server tried to validate your post data and it's wrong.
usually this response contains body with explanation...
for 400+ status codes the body comes through getErrorStream() and not through getInputStream()
So, I would do it like this:
def postRequest(url, message) {
def post = new URL(url).openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + userpass.getBytes("UTF-8").encodeBase64()
post.setRequestProperty("Authorization", basicAuth);
post.setRequestProperty("Content-Type", "application/json")
post.setDoOutput(true)
if( !(message instanceof String) )message = new groovy.json.JsonBuilder(message).toPrettyString()
post.getOutputStream().write(message.getBytes("UTF-8"))
def response=[:]
response.code = post.getResponseCode()
response.message = post.getResponseMessage()
if( response.code>=400 ){
try{
response.body = post.getErrorStream()?.getText("UTF-8")
}catch(e){}
}else{
response.body = post.getInputStream()?.getText("UTF-8")
}
assert response.code in [200,201] : "http call failure ${response.code}: ${ response.body ?: response.message }"
return response
}
def msg = [
fields: [
project : [ id: "001" ],
summary : "Test Issue For Jira Integration",
description : "Creating of an issue for for projects and issue types using the REST API",
issuetype : [ id: "5" ]
]
]
def r = postRequest("http://httpbin.org/post", msg)
println r
The issue was related to certificate , I have to bypass the certificate validation and its working fine. Since both the application are under same network and behind same company's firewall , I have bypass the certificate validations.
Adding the skipping certificate validation part to the above code is working for me

ionic 3 header not sending Authorizaqtion 'bearer "token"' to server

Im doing a login screen that takes a username and password.
if the login was successful the server will return a token.
then im trying to call another function to get user info but the authorization header is not being passed.
im trying my server method on postman and its working fine so i believe the problem is in the headers. May someone please advise me on what should be done?
let url = urlConst.Login;
let params1 = new HttpParams();
let loader = this.loadingcontroller.create({
content: stringEngConst.signinngin
});
let attributes = {
username: this.uname.value.toLowerCase(),
password: this.password.value,
grant_type: "password"
};
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = 'username=' + this.uname.value.toLowerCase() + '&password=' + this.password.value + '&grant_type=password';
let data: Observable < any > = this.http.post(url, body, {
headers: headers
});
loader.present().then(() => {
data.subscribe(result => {
if (result.access_token != null) {
this.signintoken = result.access_token;
this.storage.set(storageConst.SIGN_IN_TOKEN, result.token_type + " " + result.access_token);
headers.append('Authorization', 'Bearer ' + this.signintoken);
let url1 = 'http://localhost:57940/API/Account/GetUserInfo/';
let info: Observable < any > = this.http.get(url1, {
headers: headers
});
info.subscribe(result => {
/*Do Something*/
});
}
Please Note that result.access_token != null is true. and i am successfully getting the token back. But it is not being passed again to the second url (info)
Looks like this SO post may solve things for you: https://stackoverflow.com/a/47805759/6599076
You may want to use:
headers = headers.append('Authorization', 'Bearer ' + this.signintoken);
You are using the same headers as for the first http request:
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
Depending on your end point for the subsequent call it might be that you need to set headers differently:
Try creating new headers with
var headers2 = new HttpHeaders();
headers.append('Content-Type', 'application/json');
Or get rid of Content-Type completely depending on what your end point expects.
Also if you are using Ionic 3 its worth to check which Http module you are using (HttpClient or the older one) as there are some differences in how these tend to handle request options.

Getting 500 error while creating vertex using Rest API

I am writing a SSIS script component for importing data into orientdb using RestAPI but i am getting error 500. Please i am stuck here. Is there anyone who can help me with this. I am using version 2.1.7 community edition.
Here is my code so far.
Uri address = new Uri("http://localhost:2480//command/SQ-DB/sql/");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json; charset=UTF-8";
request.ContentType = "application/json";
string username = "root";
string password = "***";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
StringBuilder data = new StringBuilder();
// string link = "{\"statements\" : [ {\"statement\" : \"CREATE ( company: Accounts { Name:" + Row.companyname + "} ) RETURN company\"} ]}";
string link= "CREATE VERTEX Contacts CONTENT { 'name' : "+ Row.fullname+", 'Email' : "+ Row.emailaddress1+", 'Phone' : "+ Row.telephone1 + ", 'ContactId' : "+ Row.contactid+", 'City' : "+Row.address1city+"}" ;
data.Append(HttpUtility.UrlEncode(link));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
request.Headers.Add("Accept-Encoding", "gzip,deflate");
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
It will be a great help if anyone can point the issue. Thank you