im currently trying to call on a API using "GET" method in javascipt, but i don't seem to get any access. This is the code.
loadLibrary("cus:json3.js");
try {
var buffer = new MemoryBuffer();
buffer.fromString("username" + ':' + "password", "utf-8");
var http = new HttpClientRequest();
http.header["Authorization"] = "Basic " + buffer.toBase64();
this.baseURL = "https://url...";
http.url = this.baseURL;
http.method = "GET";
http.execute();
logInfo();
var response = http.response;
}
} catch(e) {
logInfo(e);
}
But all i get is -55 error. Not sure why I can't access the API like this. Does anybody have an idea that would be awsome. The firewall has allowed the IP that my program is using.
Related
I am trying to connect to an API to display some data on my website.
I've already defined Http as new XMLHttpRequest();, and url as the API endpoint.
Here's the code:
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.stringify(Http.responseText)
document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}
However, when I run the code, I get the following error:
Uncaught TypeError: api.total_bandwidth is undefined
What is wrong here? Is Http.responseText already an Object? Did I define the API wrong?
This is the response of api:
{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}
You're stringifying the object (response), then trying to get "TB" from a string.
Try parsing api then getting the properties from it:
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.stringify(Http.responseText);
var apiJson = JSON.parse(api);
document.getElementById("stat").innerHTML = "Powering over " + apiJson.total_bandwidth.TB + "TB of private internet traffic";
};
Edit: Turns out that "JSON.stringify" was actually a mistake.
I think you meant to use JSON.parse rather than JSON.stringify... - Robin Zigmond
I think you meant JSON.parse (to PARSE the response text) instead of JSON.stringify:
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.parse(Http.responseText);
document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}
Learn more about JSON.parse at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I'm working with ARIS tool and I want to make calls(GET, POST...) in ARIS to ARIS API repository!
I have authentication that works when I try it directly in the repository, but I got an error when I debug the code I have in ARIS.
The error: Error running script: Connection refused: connect.
I have the following code:
var obj = new java.net.URL(url);
var con = obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", java.net.USER_AGENT);
var tenant = "";
var name = "";
var password = "";
var key = "";
var authString = tenant + ":" + name + ":" + password + ":" + key;
var encoder = new java.lang.String(Base64.encode(authString));
con.setRequestProperty("Authorization", "Basic" + encoder);
var responseCode = con.getResponseCode();
var iN = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
var inputLine = new java.lang.String();
var response = new java.lang.StringBuffer();
while((inputLine = iN.readLine()) != null){
response.append(inputLine);
}
iN.close();
return new java.lang.String(response);
Is the problem that I use Basic authentication, but I have tenant and key also or it's something else?
Also, name, password, key and tenant I'm leaving empty for security purposes, but in the original code the values are inserted. Also the url parameter contains the url link that is called directly in the repository.
Can someone please help me?
Thanks!
any thoughts as to why this script emails an attachment but the attachment is not the correct spreadsheet, and looks like some sort of google error page.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
Logger.log(url);
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("youremail#email.com", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
I guess API has changed. You can try Drive REST API(v3) instead. Replace
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
var params = { ... };
var blob = UrlFetchApp.fetch(url, params).getBlob();
to
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() +
"/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" +
"{your API key}";
var blob = UrlFetchApp.fetch(url).getBlob();
I tested and it worked. Of course you first should get your own API key, etc, at API Manager. Then you can try some APIs like simple GET requests at APIs Explorer. Or you can try some APIs, in this case Files: export, also at the documentation page itself, but notice that you cannot try your own API key here.
This is the updated code that #sangbok helped with:
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var sheet = DriveApp.getFileById(ss.getId());
// sets sharing to public - to send out email.
sheet.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" + "YOURAPIKEYGOESHERE4";
var blob = UrlFetchApp.fetch(url).getBlob();
Logger.log(url);
blob.setName(ss.getName() + ".xlsx");
var now = new Date();
MailApp.sendEmail("YOUREMAILADDRESSGOESHERE", "EMAIL SUBJECT " + now , "EMAIL BODY " + now , {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
// returns the file back to Private access
sheet.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.EDIT);
}
I'm trying to add a user who clicks on a button in a SharePoint (online) site to a Office 365 group. I know this can be done via JSON using the Add Member API.
https://github.com/OfficeDev/microsoft-graph-docs/blob/master/api-reference/v1.0/api/group_post_members.md
I am however really inexperienced when it comes to JSON and keep messing up the POST function. This is the code I have currently, everything before the comma has been working fine.
function showButton() {
$('btn-1').on('click', function(event) {
var userProfileProperties
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
userProfileProperties = peopleManager.getMyProperties();
clientContext.load(userProfileProperties);
clientContext.executeQueryAsync(onSuccess, onFail);
function onSuccess(){
accountProperties = userProfileProperties.get_userProfileProperties();
accountId = accountProperties['msOnline-ObjectId'];
//JSON Query
jQuery.ajax({
url: "https://mysite.sharepoint.com/groups/groupID/members/$ref";
method: "POST";
contentType: "application/json";
dataType: 'json',
{
"#odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/" + accountId
};
});
};
function onFail(){
alert(failed);
};
});
};
In your document , you will find authentication token is required in the Request headers .Without authentication token ,you will receive an error as :
"code": "InvalidAuthenticationToken", "message": "Bearer access token is empty."
As a solution , you could try following steps :
1.Register a javascript Application in Azure AD and configure your app to allow the OAuth 2.0 implicit grant flow.Tokens are obtained using the OAuth 2.0 implicit grant flow. Using implicit grant, your application requests an access token from Azure AD for the currently signed-in user by sending the user to an authorization URL where the user signs in with their Office 365 credentials and then is redirected back to the app with the access token in the URL .
2.Add permissions to Graph API .
3.Add an html page to your sharepoint online(using Explorer mode) .
4.Edit the html , write below function to get an access token:
function requestToken() {
// Change clientId and replyUrl to reflect your app's values
// found on the Configure tab in the Azure Management Portal.
// Also change {your_subdomain} to your subdomain for both endpointUrl and resource.
var clientId = '3dadb44e-feaa-4158-90f5-e129e15db66d';//ID of your App in Azure
var replyUrl = 'https://o365e3w15.sharepoint.com/sites/XXX/app.html'; //my sharepoint page that requests
//an oauth 2 authentification and data
//It is also referenced in the REPLY URL field of my App in Azure
var endpointUrl = 'https://graph.microsoft.com/v1.0/me/messages';
var resource = "https://graph.microsoft.com/";
var authServer = 'https://login.windows.net/common/oauth2/authorize?';
//var authServer = 'https://login.microsoftonline.com/common/oauth2/authorize?';//this works either
var responseType = 'token';
var url = authServer +
"response_type=" + encodeURI(responseType) + "&" +
"client_id=" + encodeURI(clientId) + "&" +
"resource=" + encodeURI(resource) + "&" +
"redirect_uri=" + encodeURI(replyUrl);
window.location = url;
}
After that ,you could make an ajax call to graph api endpoint to get/post request, for example, get current user's messages:
var endpointUrl = "https://graph.microsoft.com/v1.0/me/messages";
var xhr = new XMLHttpRequest();
xhr.open("GET", endpointUrl);
var myToken = getToken();
// The APIs require an OAuth access token in the Authorization header, formatted like this:
//'Authorization: Bearer <token>'.
xhr.setRequestHeader("Authorization", "Bearer " + myToken);
// Process the response from the API.
xhr.onload = function () {
if (xhr.status == 200) {
//alert('data received');
var message="";
var object = JSON.parse(xhr.response);
for(i=0;i<object.value.length;i++){
message+='Subject: ' + object.value[i].subject + '<br>';
}
document.getElementById("results").innerHTML = message;
} else { }
}
// Make request.
xhr.send();
display this app.html into any SharePoint Webpart page by calling it within an iframe tag.
All detail steps you will find in this article , i have tested and work fine in my side .
I'm trying to write an old native Android app with Ionic and I need help for the http request. I'm newbie in AngularJS (js too).
My Android code has a function like:
String address = "http://www.example.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(responsegetEntity().getContent()));
StringBuilder sBuilder = new StringBuilder();
String sLine = "";
while ((sLine = rd.readLine()) != null) {
sBuilder.append(sLine).append("\n");
}
String sContent = sBuilder.toString();
(...parsing sContent...)
} catch (Exception e) {
//something
}
and if there are more then one page I call a function like
String address = "http://www.example.com/result.do?page="+ iPage;
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
Cookie ck = client.getCookieStore().getCookies().get(0);
pairs.add(new BasicNameValuePair("param_ck", ck.getValue()));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
(..parsing..)
}
So, I read the html content of a webpage (I'm not the owner) and I do somethings with that.
I tried $http.post but I'm not sure if it's the same
.factory('Service', function($q,$http) {
return {
getResult: function(param) {
var q = $q.defer();
var address = "http://www.example.com";
var sParam = "param";
$http({
url: address,
method: "POST",
data: {
'param' : sParam
}
})
.then(function(response) {
(...)
q.resolve(position);
},
function(error) {
(...)
q.reject(error);
});
return q.promise;
}
};
});
PS: I get the
No 'Access-Control-Allow-Origin' header is present on the requested resource.
with that.
Can you help me?
I am not entirely sure why you don't get a similar error with your Android code, or even if you were supposed to, as I am not familiar with native Android itself. But the reason that you get this with Angular in Ionic is that the server requires to implement CORS to get rid of that.
From MDN:
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves. For example, an HTML page served from http://domain-a.com makes an src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains.