Transfer ownership of file uploaded using Google drive API - 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.

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.

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;
}

Video Uploading Status in Vimeo

I am uploading video in Vimeo using my Application,But some of my videos status are not getting updated
I have followed the api document provided in this link: https://developer.vimeo.com/api/upload/videos:
I am using below code:
public boolean sendVideo(String file1, String completeURi, String endpoint, String id) throws FileNotFoundException, IOException {
File file = new File(file1);
long contentLength = file.length();
String contentLengthString = Long.toString(contentLength);
FileInputStream is = new FileInputStream(file);
int bufferSize = 20485760;
byte[] bytesPortion = new byte[bufferSize];
int byteNumber = 0;
while (is.read(bytesPortion, 0, bufferSize) != -1) {
String contentRange = Integer.toString(byteNumber);
boolean success = false;
int bytesOnServer = 0;
while (!success) {
long bytesLeft = contentLength - (bytesOnServer);
System.out.println(newline + newline + "Bytes Left: " + bytesLeft);
if (bytesLeft < bufferSize) {
//copy the bytesPortion array into a smaller array containing only the remaining bytes
bytesPortion = Arrays.copyOf(bytesPortion, (int) bytesLeft);
//This just makes it so it doesn't throw an IndexOutOfBounds exception on the next while iteration. It shouldn't get past another iteration
bufferSize = (int) bytesLeft;
}
bytesOnServer = sendVideoBytes("Vimeo Video upload", endpoint, contentLengthString, "video/mp4", contentRange, bytesPortion, first,isuploaded);
AppLog.e("bytesOnServer", "===contentLength===" + bytesOnServer +"&&=="+contentLengthString);
if (bytesOnServer >= Integer.parseInt(contentLengthString)) {
System.out.println("Success is true!");
return true;
} else {
contentRange = (bytesOnServer + 1) + "-" + (Integer.parseInt(contentLengthString)) + "/" + (Integer.parseInt(contentLengthString));
System.out.println(bytesOnServer + " != " + contentLength);
System.out.println("Success is not true!"+contentRange);
success=false;
first = true;
}
}
}
return true;
}
/**
* Sends the given bytes to the given endpoint
*
* #return the last byte on the server (from verifyUpload(endpoint))
*/
private static int sendVideoBytes(String videoTitle, String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange,boolean isuploaded) throws FileNotFoundException, IOException {
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", contentLength);
request.addHeader("Content-Type", fileType);
if (addContentRange) {
request.addHeader("Content-Range", "bytes " + contentRange);
}
request.addPayload(fileBytes);
Response response = signAndSendToVimeo(request, "sendVideo with file bytes " + videoTitle, false);
if (response.getCode() != 200 && !response.isSuccessful()) {
return -1;
}
return verifyUpload(endpoint, contentLength, contentRange,isuploaded);
}
/**
* Verifies the upload and returns whether it's successful
*
* #param
* #param contentLength
* #param endpoint to verify upload to #return the last byte on the server
*/
public static int verifyUpload(String endpoint, String contentLength, String contentRange,boolean isuploaded) {
// Verify the upload
OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
request.addHeader("Content-Length", "0");
request.addHeader("Content-Range", "bytes */*");
Response response = signAndSendToVimeo(request, "verifyUpload to " + endpoint, true);
AppLog.e("verifyUpload", "" + response.getCode());
if (response.getCode() != 308 || !response.isSuccessful()) {
return -1;
}
String range = response.getHeader("Range");
AppLog.e("After verify","==range header contains"+Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)));
//range = "bytes=0-10485759"
return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)); //+1 remove
//return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)) + 1;
//The + 1 at the end is because Vimeo gives you 0-whatever byte where 0 = the first byte
}
public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
String newline = "\n";
System.out.println(newline + newline
+ "Signing " + description + " request:"
+ ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
+ ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
service.signRequest(OAuthConstants.EMPTY_TOKEN, request);
Response response = request.send();
// AppLog.e("Uplaod Video aftre Response", "" + response.getCode());
return response;
}
Can anyone help with a working code for Android??
Thanks in advance!!
I recently had the same problem with vimeo. The api returns the state VIMUploadState_Succeeded for the upload process, but if you try to watch the video at vimeo.com it is stucked in the uploading state and it shows a black screen in the app when you try to reproduce the video.
I got the following answers from their support team:
It looks like this specific video
didn't change from the uploaded state to a failure state.
Sorry but the videos provided in those links never finished uploading
and are lost. They will need to be re-uploaded.
In our platform there are several videos uploaded everyday and it seems to have no pattern to identify when this uploading problem will happen. If it is not a problem for you to re-upload the video, vimeo can be a good solution since its price is really good in comparison to other video platforms, otherwise you should look for another video storage/playback solution.
It is difficult to check up your code without proper debugging.
Here's the workaround for your code with a little more functions added
You can check the code here

How to read from openTSDB with a JSON POST?

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());

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) + "..." ...