I am trying to make an HTTP call to get the files content in drive using the below code:
string strbearer = 'Bearer '+strKey;
string strfileID = '1aIl4Sv**********hW';
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://www.googleapis.com/drive/v3/files/strfileID');
req.setHeader('content-type', 'text/plain');
req.setHeader('Authorization',strbearer);
req.setTimeout(60*1000);
HttpResponse resp = http.send(req);
but when i execute the above code i'm getting error as invalid credentials. please let me know if, this is the correct way to make a get request to drive using Apex(salesforce).
Related
I have a flutter app and I'm using back4app.com and Parse RESTful api to register my users, I have read their docs about logging in users but I dont know how to pass my username and password in URL parameters as JSON encoded :
I tried this method:
Future <void>loginMethod(String username,String password) async {
var url = Uri.parse('https://myshoppingapp.b4a.io/login/$username:$password');
final response = await http.get(url, headers: {
'X-Parse-Application-Id': kParseApplicationId,
'X-Parse-REST-API-Key': kParseRestApiKey,
'Content-Type': 'application/json'
},);
final exData = jsonDecode(response.body);
print(exData);
but I've got some errors
Don't use the GET method while sending your personal data to the server.
GET method data is sent data to the server followed by the URL like append with URL request which will be seen to everyone like below.
var url = Uri.parse('https://myshoppingapp.b4a.io/login/$username:$password');
This is how your personal data can be readable from a URL in a GET Method.
'https://myshoppingapp.b4a.io/login/Mehran#metra.org:abcd12345'
For login requests, we should use the POST method. Because our login data is secure which needs security. When using the POST method the data is sent to the server in a bundle.
Future loginMethod(String username,String password) async {
var res = await http.post(Uri.parse('https://myshoppingapp.b4a.io/login/'),
body: {"username": username, "password": password});
print('res : ${res.body}');
if (res.statusCode == 200){ final exData = jsonDecode(res.body);
print(exData);
return res.body;
} else{
final exData = jsonDecode(res.body);
print(exData);
return res.statusCode;
}
}
for HTTP basic authentication
final loginUrl = Uri(scheme: 'https', host: 'example.com', port: 8080, userInfo: 'username:password')
http.get(loginUrl)
but pass username and password via url is not recommended cause it's not safe.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#access_using_credentials_in_the_url
so you should do it by using post formdata.
My goal:
I want to make a get request to the RestApi that is running on the device in my local network to retrieve JSON data generated by the device.
What happens
The RestApi correctly responds to the browser call from every other device in the network. Bash's curl also works, however when I try to access the data through dart's http.get the program fails to retrieve the JSON data - I'm getting Statuscode 400.
Browser call result
What I have tried:
Messing with URL to make sure it's written correctly,
Setting up headers {"content" : "application/json"}
Using no (default) headers
Running the API call from separate dart file and from function embedded in flutter app. Both resulted in Statuscode 400, though flutter provided some more bug information:
Unhandled Exception: SocketException: OS Error: No route to host, errno = 113. I believe I have also seen the errno = 111 when I tried something else.
Using lower level HttpClient instead of Http
In the flutter app, I can connect to the data stored on firebase through http.get easily enough, but call to the device in local network results in the scenario described above.
Stand-alone dart file
import 'package:dart_http/dart_http.dart' as dart_http;
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
main(List<String> arguments) async {
var url = 'http://192.168.0.5/api/device/state';
http.Response response1 =
await http.get(url, headers: {"content": "application/json"});
print('Response status: ${response1.statusCode}');
print('Response body: ${response1.body}');
print('Response body: ${response1.headers}');
print('Response body: ${response1.reasonPhrase}');
print('Response body: ${response1.request}');
HttpClient()
.getUrl(Uri.parse(
'http://192.168.0.5/api/device/state/')) // produces a request object
.then((request) => request.close()) // sends the request
.then((response) {
print(response);
response.transform(Utf8Decoder()).listen(print);
}); // transforms and prints the response
}
Call-embedded in flutter project
Future<Map<String, String>> getAirSensorStatus() async {
print("Getting Air Sensor");
http.Response response =
await http.get('http://192.168.0.5/api/device/state');
print(response);
print("Status code " + "${response.statusCode}");
try {
if (response.statusCode != 200 && response.statusCode != 201) {
print("Something went wrong. Status not 200 and not 201 for AirSensor");
return null;
}
final responseData = json.decode(response.body);
return responseData;
} catch (error) {
print(error);
return null;
}
}
I'm expecting to get statuscode 200 and JSON data in the response. Instead, only a response object is created and no connection established.
Could you help me figure out why is that?
The link to the documentation of the API I'm trying to access:
https://technical.blebox.eu/
The issue seems likely to be caused by the client unable to reach the local server on the request. HTTP error 400 is labelled as "Bad request" and "No route to host, errno = 113" usually caused by network error. A common fix to this issue is to ensure that the client is on the same network the local server is hosted in.
Trying to create a function in apex that will create Google Drive folders when creating a new record in Salesforce.
I have managed to authenticate and handle GET requests just fine. My issue is regarding the POST requests. The code below should create a folder with the label provided in the "title" parameter. The script executes and instead creates an extension-less file without a label.
public void getDriveFiles(HttpResponse authResponse) {
http h = new Http();
Httprequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Map<String, Object> responseObject = (Map<String, Object>) JSON.deserializeUntyped(authResponse.getBody());
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setHeader('Authorization', 'Bearer '+responseObject.get('access_token'));
String jsonData = '{"title":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
req.setBody(jsonData);
res = h.send(req);
system.debug('Response ='+ res.getBody() +' '+ res.getStatusCode());
}
I have a feeling it's my request body but I have no idea what to do to fix it.
You've used the wrong endpoint. Instead of the file endpoint, you're posting to the content endpoint.
So
req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
should be (for the v2 API)
req.setEndpoint('https://www.googleapis.com/drive/v2/files');
or (for the v3 API)
req.setEndpoint('https://www.googleapis.com/drive/v3/files');
If you use v3 (which you probably should), your json should change thus
String jsonData = '{"name":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
HTTP "POST" data with login credentials to the BASEn server using API URL, in response it is giving a status 200, OK.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mode", "login"),
new KeyValuePair<string, string>("user", logintxtbx.Text),
new KeyValuePair<string, string>("password", passtxtbx.Text)
};
httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync("https://xx-yyy.com/auth", new FormUrlEncodedContent(values)); var strin = response.StatusCode.ToString();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show("login Success");
GetFullResponse(httpClient);
}
After validating my credentials, the server will create a session to me if i try to do "GET" HTTP by using another urls, it should gives my required data but this thing was not happening, every time iam getting "403" forbidden response.
This is the code using for "GET" data.
var uri = new Uri("https://xx-yyy.com/_ua/web/web/v1/xyz/?xyx=1431369000000&end=1431436740000&_=1431436741550");
var Response = await httpClient.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode()
var ResponseText = await Response.Content.ReadAsStringAsync();
i don't know whats wrong, i was doing.
Can any one suggest me how can i do this to be happen.
var handler = new HttpClientHandler();
var cookieContainer = handler.CookieContainer;
var client = new HttpClient(handler);
store cookies using cookieContainer and use them to authenticate the future calls using the same way as on web.
Store the cookies to the phone using IsolatedStorageSettings
Reference for more details here
I am developing an iOS Application using MonoTouch. The application collects its data from a web service, using this code:
private static string getResult (string url)
{
string result;
var request = HttpWebRequest.Create (url);
request.ContentType = "application/json";
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
return result;
}
And this works fine, BUT when the json string returned from the Web Service reaches a certain size, the request returns with Internal server error 500. I have tried to invoke the service method directly in a web browser, and this returns a json string as expected. Why will it not work with my code, and is there a way to fix this?
Update:
I think this might solve my problem: http://forums.iis.net/t/1176077.aspx/1
Try Increasing Time Out for your service request. Your service must be timing out resulting 500 error
Also check this http://www.checkupdown.com/status/E500.html