How to handle response Content Type Audio when accessing REST API? - rest

Am using Voice RSS to do text to speech translation for my java application. I have used clients like RESTY in my past to handle simple json requests which am comfortable with. But in this case, the server (Voice RSS) is returning content type as audio, am unsure how to handle and unwrap this as a java client. Any help would be greatly appreciated
Thanks
Karthik

I figured out that you can use Url and BufferedInputStream to download the response from the web service as a byte array or as an OutputStream which you can save it as anything.
InputStream in = null;
ByteArrayOutputStream outputStream = null;
byte[] byteArray = null;
try {
URL link = new URL("YOUR_URL");
in = new BufferedInputStream(link.openStream());
outputStream = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
outputStream.write(buf, 0, n);
}
byteArray = outputStream.toByteArray();
}catch (Exception ex){
throw ex;
}finally {
if(in != null) in.close();;
if(outputStream != null) outputStream.close();
}

Related

how to upload Image and data as Multipart in swift Alamofire

I am an android guy and I have achieved this in android I need to convert this code into swift now for my ios project, I have tried uploading my the data and the image using Alamofire in ios and I have been struggling since a week if you guys can help me out here.
my data looks like this
First String-
---------SWPMCF1Le5z\r\nContent-Disposition: form-data; name=\"files\"; filename=\"IMG_20171021_192906.jpg\"\r\nContent-Type: image*\/\/*\r\n\r\n"
"This is my image data in bytes"
Second String
---------SWPMCF1Le5z
Content-Disposition: form-data; name="json"
Content-Type: application/json
{"thread":{"title":"hh","site_id":177},"comment":{"shift_id":4,"subject":"hh","message":"gt","entered_at":"2017-11-02 10:52:56","priority":"high","author_id":1621,"entities":[],"fields":[],"files":[],"images":[{"filename":"IMG_20171021_192906.jpg"}],"fileData":[{"data":"\/storage\/6535-3331\/DCIM\/Camera\/IMG_20171021_192906.jpg"}]}}
---------SWPMCF1Le5z--
Now I need to send this using Alamofire to server but I was getting
Error code -1001
of which I have no clue.
I tried several ways into Alamofire like using multipart, standard way then I tried standard way of hitting the server in swift with no luck Please if you guys can help me out.
I did the same thing in the android in standard way.
Here is my android code if you guys and figure out.
InputStream fStream = null;
try {
DataOutputStream out = new DataOutputStream(http.getOutputStream());
for (int i = 0; i < body.length(); i++) {
String string = body.optString(i);
//Here I am writing the image data into http outputstream
if (string.startsWith("[FILE]")) {
File file = new File(string.replace("[FILE]", ""));
fStream = new FileInputStream(file);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length;
while ((length = fStream.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
fStream.close();
} else {
//Here I am writing the the first and second string.
out.writeBytes(string);
}
}
out.flush();
out.close();
} catch (ConnectException e) {
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
if (fStream != null) fStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Please guys help me out here and let me know if any more code is need.
Thanks in advance.

Java - Bing Spatial Data Services : <title>Object moved to....</title>

I'm trying to use Bing Spatial Data Service of Microsoft by using Java from my server. (I used this code : How to send HTTP request in java?) but it doesnt work at all.
What I want to do: get latitude and longitude from a given adress
public static void main(String[] args) throws IOException {
System.out.println(SendRequete());
}
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
HttpURLConnection connection = null;
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
I keep having the same results:
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
</body></html>ed to here.</h2>
ml><head><title>Object moved</title></head><body>
If I copy and paste on y browser it works fine... Any idea of where the problem is
Looks like you are using the Bing Maps REST services not the Bing Spatial Data Services. The REST services can geocode individual locations on demand, while the Spatial Data Services can geocode up to 200,000 locations in a single request.
Assuming you mean the REST services, yes, the URL you are creating is correct. However you are passing in part of the URL as URL parameters when you shouldn't be. Also, you need to make a GET request, not a POST request. Here is a modified version of your code that should work.
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
URL url = new URL(targetURL + urlParameters);
URLConnection connection = url.openConnection();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}

want to store images to gridfs from a given URL

Is it possible to store images to mongo GridFS directly form URL, which I get from API? or I have to store it locally and then insert it into mongo?
I tried to insert directly from URL, but C# driver gave me an error that URI is not supported..
The MongoGridFS class implements .NET's stream API so you should be able to use a MemoryStream to save the web response and insert into GridFS.
try
{
var server = MongoServer.Create("mongodb://192.168.1.8:27017/imgdb?safe=true");
var db = server.GetDatabase("imgdb");
string fileName = "logo-mongodb.png";
// Get image from URL or API
WebRequest req = WebRequest.Create("http://media.mongodb.org/" + fileName);
WebResponse response = req.GetResponse();
Console.WriteLine("Response length is " + response.ContentLength + " bytes");
// Copy from WebResponse to MemoryStream
MemoryStream memStream;
using (Stream responseStream = response.GetResponseStream())
{
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do
{
byteCount = responseStream.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
responseStream.Close();
}
// Reset to beginning of stream
memStream.Seek(0, SeekOrigin.Begin);
// Save to GridFS
var gridFsInfo = db.GridFS.Upload(memStream, fileName);
// Success!
Console.WriteLine("Success!");
}
catch (Exception err)
{
Console.WriteLine("Something went wrong: "+err.Message);
}

upload image to Database by using WCF Restful service

I am using WCF restful service to upload image to my databse
Code:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "AddDealImage/{id}")]
long AddDealImage(string id, Stream image);
public long AddDealImage(string id, Stream image)
{
//add convert Stram to byte[]
byte[] buffer = UploadFile.StreamToByte(image);
//create image record for database
Img img = ImgService.NewImage(DateTime.Now.ToFileTime().ToString(), "", buffer, "image/png");
ImgService.AddImage(img);
//return image id
return img.ImageId;
}
public static byte[] StreamToByte(Stream stream)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Problem:
When i upload my photo via iPhone the POST was Successful. New image id is returned, and I can see the new record created in the database.
However when I try to convert binary from DB record to Image Stream: I got error:
"No imaging component suitable to complete this operation was found."
it seems that the MemoryStream is corrupted.
//photoBytes from database
MemoryStream photoStream = new MemoryStream(photoBytes)
//Error happened here
var photoDecoder = BitmapDecoder.Create(
photoStream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.None);
Plus, the error only happens when image is uploaded via WCF Restful service.
It works perfectly if the image is uploaded via web form.
Question:
Where did i do wrong or missed?
how can i write a test client to test this upload api?
many thanks
the code above actually works.
the part I missed is the transferModel you need to set it to "Streamed" in web.config
Code for testing:
static void Main()
{
string filePath = #"C:\Users\Dizzy\Desktop\600.png";
string url = "http://localhost:13228/ApiRestful.svc/AddDealImage/96";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "text/xml";
request.Method = "POST";
using (Stream fileStream = File.OpenRead(filePath))
using (Stream requestStream = request.GetRequestStream())
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
{
requestStream.Write(buffer, 0, byteCount);
}
}
string result;
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}