I am using Ooyala sdk for C# and got a problem with uploading image for specific content. Here is my code. will be happy to get some help:
OoyalaAPI o = new OoyalaAPI(apikey, secretkey);
byte[] bytess = File.ReadAllBytes(#"C:\Users\Daniel\Desktop\FIRE2.jpg");
Hashtable booody = new Hashtable();
string exception = "";
object p = o.postBytes("assets/I2ZDlzbjrIFtbAxzrkJ3NLzEDR30jFYh/preview_image_urls", new Dictionary<string, string>(), bytess, out exception, null); //Upload File
booody.Add("type", "uploaded_file");
o.put("assets/I2ZDlzbjrIFtbAxzrkJ3NLzEDR30jFYh/primary_preview_image", new Dictionary<string, string>(), booody, out exception); //Pick The Thumbnail File
The Exception i get is (400) Bad Request from the function response = request.GetResponse()
as HttpWebResponse;
I will appreciate some help with this issue.
Changed preview_image_urls to preview_image_files...
Works good now.
Related
I am newbie to web service. Due to requirement I have to send a file[most probably in txt format] to server through REST web service.
I am getting the exception like below.
MessageBodyWriter not found for media type=application/json, type=class gvjava.org.json.JSONObject, genericType=class gvjava.org.json.JSONObject.
Here is my web service method.
#Path("{c}")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String convert(#PathParam("c") JSONObject object) throws JSONException {
String result = "";
return "<ctofservice>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>";
}
Now client code is like below
JSONObject data_file = new JSONObject();
data_file.put("file_name", uploadFile.getName());
data_file.put("description", "Something about my file....");
data_file.put("file", uploadFile);
Client client = ClientBuilder.newClient();
webTarget = client.target(uploadURL).path("ctofservice").path("convert");
Response value = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(data_file,MediaType.APPLICATION_JSON_TYPE),
Response.class);
Please help me with this.
Thanks in advance.
------------------------------------------------------------------------
As suggested by peeskillet in the answer below, I tried to send file through multipart. Still I am facing exception of no octet stream found.
Below is my rest api
#Path("{c}")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response convert(#FormDataParam("file") FormDataContentDisposition file) {
String result = "";
Some operation with attached parameter ...
return Response.status(200).entity(result).build();
}
Here is my test client
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
uploadFile,MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(fileDataBodyPart);
Client client = Client.create();
WebResource webResource = client
.resource(uploadURL).path("ctofservice");
ClientResponse response = webResource.accept("application/json")
.post(ClientResponse.class,multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
And I am getting the exception below
I am not able to understand why I need to send data as MediaType.APPLICATION_OCTET_STREAM_TYPE ? As I have used multipart as media type before ...
I appreciate your help..
Without needing to configuring anything else, the easiest way to get around this is to just use a String instead of the actual JSONObject (i.e. just passing toString())
.post(Entity.json(data_file.toString()))
The problem with using JSONObject is that there is no provider that knows how to handle the conversion. You will have the same problem on the server side, where there is no provider to handle the conversion to JSONObject. So you will need to just do
#POST
public Response post(String json) {
JSONObject jsonObject = new JSONObject(json);
}
If you really want to be able to just use JSONObject without needing to use a String, then you should check out this post.
As an aside, this is not valid JSON (it's XML)
"<ctofservice>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>"
but you are saying that the endpoint returns JSON
I have a simple GetFile Method in a Web API that returns a file stored as binary in a database. The file can be either image, video or a recording, so I set the content type based on the extension:
[System.Web.Mvc.HttpGet]
public HttpResponseMessage GetFile(Guid Id)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var file = db.Files.Where<NonConformityFile>(item => item.Id == Id).FirstOrDefault<NonConformityFile>();
byte[] imgData = file.FileContents;
MemoryStream ms = new MemoryStream(imgData);
response.Content = new StreamContent(ms);
if (file.FileExtension == "png")
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
else if (file.FileExtension == "mp4")
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4");
else if (file.FileExtension == "caf")
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("audio/x-caf");
else
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, file.FileExtension + " is not a supported file format"));
return response;
}
This Works fine, but when adding some Security to the Method (by providing a token in the http header) it started crashing. When setting a breakpoint, I discovered that the breakpoint was actually hit twice. And the second time the token was gone from the header, causing authentication failure.
Further debugging made me find out that setting the response.Content.Header.ContentType causes the GetFile Method to be called a second time.
Is this designed behaviour, or some crazy side effects from something in my Development environment?
To reproduce, try this:
[System.Web.Mvc.HttpGet]
public HttpResponseMessage GetFile()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream());
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return response;
}
And see if the Method is run twice. I cannot see the Logic in this behaviour, and it is causing problems in my authentication.
I am accessing Rackspace Cloud APIs.
I have one api call which authenticates me on the rackspace cloud.
The method works perfectly, however, from time to time, i get this exception, randomly :
The remote name could not be resolved: 'identity.api.rackspacecloud.com'
When i am not getting this exception, the method returns the expected result, as it should be.
Is there any specific reason why it does this?
Here is my .net code:
private async Task<XDocument> AuthenticateAsync()
{
XNamespace ns = "http://docs.rackspace.com/identity/api/ext/RAX-KSKEY/v1.0";
XDocument doc =
new XDocument(
new XDeclaration("1.0", "UTF-8", "Yes"),
new XElement("auth",
new XElement(ns + "apiKeyCredentials",
new XAttribute("username", "the userName"),
new XAttribute("apiKey", "the apiKey")
)
)
);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
StringContent content = new StringContent(doc.ToString(), Encoding.UTF8, "application/xml");
// i randomly get "The remote name could not be resolved" exception
HttpResponseMessage response = await client.PostAsync("https://identity.api.rackspacecloud.com/v2.0/tokens", content);
response.EnsureSuccessStatusCode();
string stringResponse = await response.Content.ReadAsStringAsync();
return XDocument.Parse(stringResponse);
}
}
This certainly sounds like a DNS failure. Can you configure your machine to use the Google DNS servers and try again?
I am having an issue with sending a jagged Array to a wcf webservice. The method is expecting a studentId and jaggedArray of information related to the student. Here is the method signature in c#
String[][] SearchStudent(string studentId, String[][] additionalInformation);
According to KSOAP wiki page, the below piece of code should have worked. I've also tried it with Hashtable; it returned the same error message.
SoapObject additionalInformation = new SoapObject(NAMESPACE, "SearchStudent");
additionalInformation.addProperty("StudentFirstName", "John");
additionalInformation.addProperty("StudentLastName", "Doe
additionalInformation.addProperty("StudentDOB", "06101990");
SoapObject request = new SoapObject(NAMESPACE, "Authenticate");
request.addProperty("sessionId", params[0]);
request.addProperty("additionalInformation ", AuthParams);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.bodyOut = request;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
androidHttpTransport.debug = true;
(new MarshalHashtable()).register(envelope);
androidHttpTransport.call(SOAP_ACTION + "SearchStudent", envelope);
SoapObject sResult = (SoapObject)envelope.getResponse();
I am getting the message Invalid argument error message.
What am I doing wrong here?
I was able to get it to work with envelope.version 10 and not 11. Here is the link to my other post where you can find the solution.
Issue #1
When i'm uploading a file to google docs i receive status code "201" created, but when i try to open the file it seems that i'm doing something wrong, because i can't open it, and when i'm trying to download and open it on my PC i see the binary data instead of text or image. Current language is APEX, but i think it's pretty understandable.
First of all i'm getting Upload URL and then putting data to this URL;
public void getUploadURL()
{
Httprequest req = new Httprequest();
req.setEndpoint('https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false');
req.setMethod('POST');
req.setHeader('GData-Version', '3.0');
req.setHeader('Authorization', 'OAuth '+accessToken);
req.setHeader('Content-Length', '359');
req.setHeader('X-Upload-Content-Type', fileType);
req.setHeader('X-Upload-Content-Length', fileSize);
Dom.Document requestDoc = new Dom.Document();
String xml =
'<?xml version=\'1.0\' encoding=\'UTF-8\'?>'
+'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:docs="http://schemas.google.com/docs/2007">'
+'<title>'+fileName+'</title></entry>';
requestDoc.load(xml);
req.setBodyDocument(requestDoc);
Http h = new Http();
Httpresponse res = h.send(req);
System.debug('response=\n'+res.getHeader('Location'));
uploadFIle(res.getHeader('Location'));
}
public void uploadFIle(String uploadUrl)
{
Httprequest req = new Httprequest();
req.setEndpoint(uploadUrl);
req.setMethod('PUT');
req.setHeader('GData-Version', '3.0');
req.setHeader('Authorization', 'OAuth '+accessToken);
req.setHeader('Host', 'docs.google.com');
req.setHeader('Content-Length', fileSize);
req.setHeader('Content-Type', fileType);
req.setBody(''+binaryData);
Http h = new Http();
Httpresponse res = h.send(req);
System.debug('response=\n'+res.getBody());
}
As for "binaryData" property - i receive it from the page using javascript like this:
<input type="file" id="myuploadfield" onchange="getBinary()"/>
<script>
function getBinary()
{
var file = document.getElementById('myuploadfield').files[0];
fileSizeToController.val(file.size.toString());
fileNameToController.val(file.name.toString());
fileTypeToController.val(file.type.toString());
var r = new FileReader();
r.onload = function(){ binaryToController.val(r.result); };
r.readAsBinaryString(file);
}
</script>
r.onload = function(){ binaryToController.val(r.result); }; - this is the string that sends file binary data to my controller.
Issue #2
I'm trying to move one collection(folder) to another, and using this article (protocol tab instead of .NET). The issue is that i need to move collection instead of copying it and when i add my collection to another using this article, i'm currently adding reference to my collection instead of moving the whole collection from one place to another.
Please tell me what am i doing wrong.
Thank you for consideration.
Your "binary" data is being corrupted, when you are performing '' + binaryData.
In general, I have had more success using slicing of files, here is an example for webkit:
var chunk = this.file.webkitSlice(startByte, startByte + chunkSize, file_type);
// Upload the chunk
uploadChunk(startByte, chunk, callback);