How to read from openTSDB with a JSON POST? - json

I am running my openTSDB on a virtual maschine and want to read data with a JSON POST request from a client.
Baseurl is the URL to my VM.
Whenever i send this request, i get an error "Unable to pass the given JSON" in my openTSDB. So what's wrong with my request?
Thanks in advance.
EDIT: The Json-Request is supposed to represent this GET Request (which works):
baseurl+"/api/query?start=1356994800000&m=sum:Leistung";
String url = baseurl;
URL obj = new URL(url + "/api/query");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/json; charset=utf-8");
con.setRequestProperty("Accept", "application/json; charset=utf-8");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeChars("{\n" +
" \"start\": 1356994800000,\n" +
" \"queries\": [\n" +
" {\n" +
" \"aggregator\": \"sum\",\n" +
" \"metric\": \"Leistung\"\n" +
" }\n" +
" ]\n" +
"}");
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
con.disconnect();
in.close();
System.out.println(response.toString());

Related

Printing ArrayList values in SpringBoot

I created an ArrayList with the json values from an Rest API.
This is the code to read the Rest API:
#RestController
public class exemploclass {
#RequestMapping(value="/vectors")
//#Scheduled(fixedRate = 5000)
public ArrayList<StateVector> getStateVectors() throws Exception {
ArrayList<StateVector> vectors = new ArrayList<>();
String url = "https://opensky-network.org/api/states/all?lamin=41.1&lomin=6.1&lamax=43.1&lomax=8.1";
//String url = "https://opensky-network.org/api/states/all?lamin=45.8389&lomin=5.9962&lamax=47.8229&lomax=10.5226";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray states = myResponse.getJSONArray("states");
System.out.println("result after Reading JSON Response");
for (int i = 0; i < states.length(); i++) {
JSONArray jsonVector = states.getJSONArray(i);
String icao24 = jsonVector.optString(0);
String callsign = jsonVector.optString(1);
String origin_country = jsonVector.optString(2);
Boolean on_ground = jsonVector.optBoolean(8);
//System.out.println("icao24: " + icao24 + "| callsign: " + callsign + "| origin_country: " + origin_country + "| on_ground: " + on_ground);
//System.out.println("\n");
StateVector sv = new StateVector(icao24, callsign, origin_country, on_ground);
vectors.add(sv);
}
System.out.println("Size of data: " + vectors.size());
return vectors;
}
}
The last line " return vectors;" returns a list with the values i parsed and returns it like this:
But i want this more "pretty", i want it to be one Array in each line, how can i achieve this?
P.S. Its on the .html page, not on console
Your return value seems a valid Json Object. If you want it more pretty so you can read it clearly then pass it through an application that makes that json pretty.
If you call your API from Postman, it will give you a pretty Json Object which will be better formatted. This will be because you have annotated your controller with #RestController so it will deliver an application/json response which Postman will know and then it will try to make it prettier.
P.S. Its on the .html page, not on console
So you hit your API from a browser. Most browsers don't expect a Json object to be returned, so they will not make it pretty. You can't force that from your Service either.
Just hit your API from Postman, it will understand it and make it pretty.

Zuora payment-methods/credit-cards api returning 90000011 from java Client but returning success response from postman

I am in the middle of integration zuora apis with my application. These are the below 3 three apis I am using through following steps -
Step 1 Requesting for auth token
Service api (Test)- https://rest.apisandbox.zuora.com/oauth/token
Request Headers - Content-Type:application/x-www-form-urlencoded
Authorization:Basic YWYzNTg5ZWMtNTFmMC00YTc2LWFlZjEtYjk0YzZmYWE0Y2ViOlJDdGV5OGlTWFFUc00xQytTPTFYWD1POE9tRWM1c0FBWVBaaE5vV24=
Request Body - grant_type:client_credentials
Response Body - {
"access_token": "41947f41d664437a98a9da38a293c89d",
"token_type": "bearer",
"expires_in": 3598,
"scope": "entity.a083d63b-b3f5-8626-f793-65cec903f9ca platform.write service.events.read service.events.write service.genesis.read service.genesis.write service.notifications.read service.notifications.write service.usage.delete service.usage.update service.usage.write tenant.41231 user.2c92c094738e5b090173902066c201ba",
"jti": "41947f41d664437a98a9da38a293c89d"
}
Use access_token or jti value from auth token response and pass it on to the headers parameters as Authorization: Bearer
Step 2 : - Request for hmac-signatures for making payment
Service api (Test) - https://rest.apisandbox.zuora.com/v1/hmac-signatures
Request Headers - Content-Type:application/json
Authorization:Bearer 41947f41d664437a98a9da38a293c89d
Request Body - {
"accountKey": "A00000485",
"method": "POST",
"uri": "https://rest.apisandbox.zuora.com/v1/payment-methods/credit-cards"
}
Response Body - {
"signature": "MDgzN2ZkYjAzOTQ5NmQ5NDQyZjc5YTU3NjUwMDgxOGIxNTY3YWM2Mw==",
"token": "C41mzDTudB2uc0Jc6vwrhQGvwq3JTxsF",
"success": true
}
The signature needs to be added in Make Payment header asSignature:MDgzN2ZkYjAzOTQ5NmQ5NDQyZjc5YTU3NjUwMDgxOGIxNTY3YWM2Mw==
The token needs to be added in Make Payment header as Token:C41mzDTudB2uc0Jc6vwrhQGvwq3JTxsF
Step 3:- Make payment request –
Service Api - https://apisandbox-api.zuora.com/rest/v1/payment-methods/credit-cards
Headers Parameters –
Host:apisandbox-api.zuora.com
Signature:MDgzN2ZkYjAzOTQ5NmQ5NDQyZjc5YTU3NjUwMDgxOGIxNTY3YWM2Mw==
Token:C41mzDTudB2uc0Jc6vwrhQGvwq3JTxsF
Content-Type:application/json
Origin:www.test.gov.uk
Cache-Control:no-cache
Request Parameters – {
"defaultPaymentMethod": true,
"cardHolderInfo":
{"addressLine1": "77 Fallon Glen",
"addressLine2": "",
"zipCode": "94020",
"state": "California",
"phone": "4155551234",
"country": "USA",
"cardHolderName": "Bill Thiebault",
"city": "Fremont",
"email": "bill#testaddress.com"},
"expirationMonth": "10",
"accountKey": "A00000485",
"creditCardType": "Visa",
"expirationYear": "2021",
"creditCardNumber": "4012888888881121",
"securityCode": "123"
}
Response Body – {
"success": true,
"**paymentMethodId": "2c92c0fb73ad855c0173b8c3316b36a1"**
}
When I use the same steps using postman I am able to get a success response. And the Payment Method id is also getting generated. Using java client the first two services are being executed. But the issue appears when I hit the request for Payment-Method / credit cards,
It always returns -
{
"success" : false,
"processId" : "84AD9CF25EC6623A",
"reasons" : [ {
"code" : 90000011,
"message" : "this resource is protected, please sign in first"
} ]
}
Please suggest me if I missed anything here.
I missed to set the header value. Here I am posting the method that I used -
It consists Oauth token generation -> generation hmac signature -> making request for payment-method / credit card. It worked for me.
public void testSpringZuorPaymentCreditCardDifferent() {
HTTPHelper httpHelper = null;
String urlOAuthToken = "https://rest.apisandbox.zuora.com/oauth/token";
String resp = null;
try {
String userNameAndPassword ="c59b646b-53c6-45fb-b9c3-d3ea0978033d" + ":" +"6VLNxA=Fbaorb7yqXO3YRaiS2a+WUfLtwOiVugLqQ";
String authorizationHeaderValue = "Basic " + new String(Base64.encode(userNameAndPassword.getBytes()));
httpHelper = new HTTPHelper(new URL(urlOAuthToken));
Map<String, String> hdmp = new HashMap<String, String>();
hdmp.put("Authorization", authorizationHeaderValue);
hdmp.put("Content-Type", "application/x-www-form-urlencoded");
httpHelper.setHeaders(hdmp);
String req = "grant_type=client_credentials";
System.out.println("REQUEST: " + req);
resp = httpHelper.post(req, 60000, 60000);
System.out.println("OAuth token response : " + resp);
}catch(Exception e) {
e.printStackTrace();
}
String[] arrOfStr = resp.split("\\W+");
System.out.println("Bearer token---------" + arrOfStr[2]);
String urlHmacSignatureUrl = "https://rest.apisandbox.zuora.com/v1/hmac-signatures";
try {
httpHelper = new HTTPHelper(new URL(urlHmacSignatureUrl));
Map<String, String> hdmp = new HashMap<String, String>();
hdmp.put("Authorization", "Bearer " + new String(Base64.encode(arrOfStr[2].getBytes())));
hdmp.put("Content-Type", "application/json");
hdmp.put("cache-control", "no-cache");
httpHelper.setHeaders(hdmp);
String req = "{\n \"accountKey\": \"A00000194\", \n \"method\": \"POST\", \n \"uri\": \"https://rest.apisandbox.zuora.com/v1/payment-methods/credit-cards\"\n}";
System.out.println("REQUEST: " + req);
resp = httpHelper.post(req, 60000, 60000);
System.out.println("Hmac Signature response : " + resp);
}catch(Exception e) {
e.printStackTrace();
}
arrOfStr = resp.split("\\W+");
System.out.println("signature : - "+arrOfStr[2]);
System.out.println("token : - "+arrOfStr[4]);
String serverURI = "https://apisandbox-api.zuora.com/rest/v1/payment-methods/credit-cards";
try {
java.util.Map<String, String> headers = new java.util.HashMap<String, String>();
httpHelper = new HTTPHelper(new URL(serverURI));
headers.put("Content-Type", "application/json");
// headers.put("Signature", arrOfStr[2]+"==");
headers.put("Signature", new String(Base64.encode("YjM4MDY5MDliZmVkYmZiOGFkNmQ1YzFhYzFmNzMyOGI3NjExM2JlNQ==".getBytes())));
headers.put("Token", new String(Base64.encode(arrOfStr[4].getBytes())));
httpHelper.setHeaders(headers);
String req = "{\r\n" +
" \"defaultPaymentMethod\":true,\r\n" +
" \"cardHolderInfo\":{\r\n" +
" \"addressLine1\":\"77 Fallon Glen\",\r\n" +
" \"addressLine2\":\"\",\r\n" +
" \"zipCode\":\"94020\",\r\n" +
" \"state\":\"California\",\r\n" +
" \"phone\":\"4155551234\",\r\n" +
" \"country\":\"USA\",\r\n" +
" \"cardHolderName\":\"Bill Thiebault\",\r\n" +
" \"city\":\"Fremont\",\r\n" +
" \"email\":\"bill#testaddress.com\"\r\n" +
" },\r\n" +
" \"expirationMonth\":\"10\",\r\n" +
" \"accountKey\":\"A00000485\",\r\n" +
" \"creditCardType\":\"Visa\",\r\n" +
" \"expirationYear\":\"2021\",\r\n" +
" \"creditCardNumber\":\"4012888888881121\",\r\n" +
" \"securityCode\":\"123\"\r\n" +
"}";
System.out.println("Req: " + req);
resp = httpHelper.post(req, 60000, 60000);
System.out.println("Payment Method - Credit Cards: " + resp);
}catch(Exception e) {
e.printStackTrace();
}
}

Apex: Get public link of a file uploaded to Google drive service account

I was able to upload an image file to google drive (Service Account) using google drive API. In return of the post, I got a filId from google.
Uploaded file to drive
I then used this fileId to create public read-only permission on the file.
added permission to file
But how do I get the public URL for the file? (I am using V3 of drive API)
I tried using "webContentLink":"https://drive.google.com/uc?id={FileID}&export=download" but the downloaded file is corrupted and not opening.
I also tried using "alternateLink": "https://drive.google.com/file/d/{FileId}/view?usp=drivesdk" but this also not working.
trying to view alternateLink
Here is my method to upload file to drive:
public static String uploadFile(String accesstoken,String FolderId, blob file, String filetype, String filename){
String thumbnailLink;
String fid;
String clink;
try{
if(String.isBlank(accesstoken) || file.size()==0 || String.isBlank(filetype) || String.isBlank(filename)){
throw new applicationException('One or more required parameters are not passed!');
}
}catch(applicationException e){
System.debug(LoggingLevel.ERROR,'Call exception ' + e.getMessage());
}
String boundary = '----------9889464542212';
String delimiter = '\r\n--' + boundary + '\r\n';
String close_delim = '\r\n--' + boundary + '--';
String bodyEncoded = EncodingUtil.base64Encode(file);
String body = '';
if(FolderId !=''){
body = delimiter + 'Content-Type: application/json; charset=UTF-8\r\n\r\n' + '{ "name" : "' + filename + '",' + ' "mimeType" : "' + filetype + '",' + '"parents":[{"id":"'+ FolderId +'"}]}' + delimiter + 'Content-Type: ' + filetype + '\r\n' + '\r\n' + bodyEncoded + close_delim;
}
else{
body = delimiter + 'Content-Type: application/json; charset=UTF-8\r\n\r\n' + '{ "name" : "' + filename + '",' + ' "mimeType" : "' + filetype + '"}'+ delimiter + 'Content-Type: ' + filetype + '\r\n' + '\r\n' + bodyEncoded + close_delim;
}
System.debug('Body: '+body);
try{
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&withLink=true');
req.setHeader('Authorization', 'Bearer ' + accesstoken);
req.setHeader('Content-Type', 'multipart/related; boundary="' + boundary + '"');
req.setHeader('Content-length', String.valueOf(body.length()));
req.setBody(body);
req.setMethod('POST');
req.setTimeout(60 * 1000);
HttpResponse resp = http.send(req);
System.debug(resp.getBody());
system.debug('Test');
Map<String, Object> p = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
thumbnailLink= (String) p.get('thumbnailLink');
fid=(String) p.get('id');
System.debug('File Id: '+fid);
clink='https://drive.google.com/uc?export=view&id='+fid;
System.debug('clink: '+clink);
} catch
(Exception e) {
System.debug(LoggingLevel.ERROR,
'Call exception ' + e.getMessage());
}
String body1 = '{"role":"reader","type":"anyone"}';
try{
//Changing file permission to public viewable using link
Http http = new Http();
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('https://www.googleapis.com/drive/v2/files/'+fid+'/permissions');
req1.setHeader('Authorization', 'Bearer ' + accesstoken);
req1.setHeader('Content-Type', 'application/json');
req1.setHeader('Content-length', String.valueOf(body1.length()));
req1.setBody(body1);
req1.setMethod('POST');
req1.setTimeout(60 * 1000);
HttpResponse resp1 = http.send(req1);
System.debug(resp1.getBody());
} catch
(Exception e) {
System.debug(LoggingLevel.ERROR,
'Call exception ' + e.getMessage());
}
return fid;
}

Transfer ownership of file uploaded using Google drive API

The Google Drive API is not able to transfer ownership of a file which was uploaded from the API itself.
as per the API documentation, PUT needs to be used for transferring ownership.
when I use it with the parameters required it returns existing permission back.
doesn't update it with new owner.
if i use POST & the required parameters it throws 'The remote server returned an error: (400) Bad Request.'
I was able to change the ownership for the files that were NOT uploaded via API. the same which I use for the files which are uploaded from API. the owner doesn't change.
Is it a bug or I am doing something wrong?
-EDIT-
if anyone wants details of file uploaded using API & file created via gdocs I can.
-EDIT2-
public bool UploadReportToGoogleDrive(Model model, byte[] ReportPDF_ByteArray, string ddlAddFilesFolder = "root", bool doNotify = true)
{
bool isErrorOccured = false;
try
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - start");
FileList fileList = new FileList();
Google.Apis.Drive.v2.Data.File uploadedFile = new Google.Apis.Drive.v2.Data.File();
Permission writerPermission = new Permission();
string accessToken = GetAccessToken();
#region FIND REPORT FOLDER
string url = "https://www.googleapis.com/drive/v2/files?"
+ "access_token=" + accessToken
+ "&q=" + HttpUtility.UrlEncode("title='My Reports' and trashed=false and mimeType in 'application/vnd.google-apps.folder'")
;
// Create POST data and convert it to a byte array.
List<string> _postData = new List<string>();
string postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
string responseString = GDriveHelper.GetResponse(request);
fileList = JsonConvert.DeserializeObject<FileList>(responseString);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder search success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\FIND REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion FIND REPORT FOLDER
if (fileList.Items.Count == 0)
{
#region CREATE REPORT FOLDER
url = "https://www.googleapis.com/drive/v2/files?" + "access_token=" + accessToken;
// Create POST data and convert it to a byte array.
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "My Reports" + "\",");
_postData.Add("\"description\": \"Uploaded with Google Drive API\",");
_postData.Add("\"parents\": [{\"id\":\"" + "root" + "\"}],");
_postData.Add("\"mimeType\": \"" + "application/vnd.google-apps.folder" + "\"");
_postData.Add("}");
postData = string.Join("", _postData.ToArray());
try
{
WebRequest request = WebRequest.Create(url);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
string responseString = GDriveHelper.GetResponse(request);
Google.Apis.Drive.v2.Data.File ReportFolder = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseString);
;
ddlAddFilesFolder = ReportFolder.Id;
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - folder creation success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
}
#endregion CREATE REPORT FOLDER
}
else
{
ddlAddFilesFolder = fileList.Items.FirstOrDefault().Id;
}
if (!isErrorOccured)
{
#region UPLOAD NEW FILE - STACKOVER FLOW
//Createing the MetaData to send
_postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + "Report_" + model.id + "\",");
_postData.Add("\"description\": \"" + " report of person - " + (model.borrowerDetails.firstName + " " + model.borrowerDetails.lastName) + "\",");
_postData.Add("\"parents\": [{\"id\":\"" + ddlAddFilesFolder + "\"}],");
_postData.Add("\"extension\": \"" + "pdf" + "\",");
_postData.Add("\"appDataContents\": \"" + true + "\",");
_postData.Add("\"mimeType\": \"" + GDriveHelper.GetMimeType("Report.pdf").ToString() + "\"");
_postData.Add("}");
postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
//// creating the Data For the file
//MemoryStream target = new MemoryStream();
//myFile.InputStream.Position = 0;
//myFile.InputStream.CopyTo(target);
//byte[] FileByteArray = target.ToArray();
string boundry = "foo_bar_baz";
url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GDriveHelper.GetMimeType("Report.pdf").ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + ReportPDF_ByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(ReportPDF_ByteArray, 0, ReportPDF_ByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
uploadedFile = JsonConvert.DeserializeObject<Google.Apis.Drive.v2.Data.File>(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - upload to folder success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\CREATE REPORT FOLDER", ex);
isErrorOccured = true;
//return "Exception uploading file: uploading file." + ex.Message;
}
#endregion UPLOAD NEW FILE - STACKOVER FLOW
}
if (!isErrorOccured)
{
#region MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE - COMMENTED
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
WebRequest request = WebRequest.Create(url);
string role = "owner", type = "user", value = "aniketpatil87#gmail.com";
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make admin account owner success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion MAKE ADMIN ACCOUNT OWNER OF UPLOADED FILE
if (model.Officer != default(int))
{
#region ALLOW OFFICER TO ACCESS UPLOADED FILE
OldModels.MWUsers officer = usersBL.GetAll(model.Officer).FirstOrDefault();
url = "https://www.googleapis.com/drive/v2/files/" + uploadedFile.Id
+ "/permissions/"
//+ uploadedFile.Owners[0].PermissionId
+ "?access_token=" + accessToken
+ "&sendNotificationEmails=" + (doNotify ? "true" : "false")
;
request = WebRequest.Create(url);
role = "writer";
type = "user";
value = Officer.EMail;
// Create POST data and convert it to a byte array.
postData = "{"
+ "\"role\":\"" + role + "\""
+ ",\"type\": \"" + type + "\""
+ ",\"value\": \"" + value + "\""
//+ ",\"permissionId\":\"" + uploadedFile.Owners[0].PermissionId + "\""
//+ ",\"transferOwnership\": \"" + "true" + "\""
+ "}";
byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = postData.Length;//byteArray.Length;
// Set the Method property of the request to POST.
request.Method = "POST";
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
//TRY CATCH - IF TOKEN IS INVALID
try
{
string responseString = GDriveHelper.GetResponse(request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - make officer writer success");
}
catch (Exception ex)
{
SingletonLogger.Instance.Error("UploadReportToGoogleDrive\\ALLOW OFFICER TO ACCESS UPLOADED FILE", ex);
isErrorOccured = true;
}
#endregion ALLOW OFFICER TO ACCESS UPLOADED FILE
}
}
if (isErrorOccured)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive failed");
}
else
{
//LogHelper.CreateLogEntry(UserContext.CurrentUser.UserID, "Uploaded " + myFileList.Count + " file(s) on Google Drive.", this.HttpContext.Request);
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - report upload to gdrive success");
}
}
catch (Exception ex)
{
SingletonLogger.Instance.Info("UploadReportToGoogleDrive - Outer exception", ex);
isErrorOccured = true;
}
return isErrorOccured;
}
Not sure if you've looked at the PATCH command for permissions. The PATCH command with the proper parameters lets you transfer ownership.
Link to Google Drive API documentation
It looks like you are specifying transferOwnership in the post body, when it must be specified as a URL parameter, as per the documentation.

badrequest error while requesting bing microsofttranslate api?

The following code returns bad request exception.Not sure what's wrong here .
string appId = "956vaQc49TdepGpsywiM+BRqfxfgOTeCr/514=";
//go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
string text = "translate this";
string language = "en";
System.Uri uri = new Uri("http://api.microsofttranslator.com/v2/Http.svc/Speak?&appId=" + appId + "&text=" + text + "&language=" + language);
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
Stream responseBody = await response.Content.ReadAsStreamAsync();
// meTextToSpeeach.Source = uri;
string strResponse;
using (Stream responseStream = responseBody)
{
using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.Unicode))
{
strResponse = sr.ReadToEnd();
}
}
}
catch (Exception)
{
}
You are not encoding the parameters (appId, text, language). You should be doing "..." + WebUtility.UrlEncode(appId) + "..." ...