Picture download from url via lotus script - url

I want to download one picture from url to my Lotus Notes application.
I can get text field from url, but image is difficult.
I try to put pic to a rich text field, but it doesn't work.
Any idea?

You can download an image from URL via LotusScript with the help of a little Script Library of type "Java".
Create a Script Library "GetImageFromUrl" of Type "Java" and put in following code:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class GetImageFromUrl {
public static boolean getImageFromUrl(String imageUrl, String filePath) {
try {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(filePath);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Then you can use the method getImageFromUrl(imageUrl, filePath) in your LotusScript code to download the image to a file. From there you can attach the image file to a RichText item with rtitem.EmbedObject(EMBED_ATTACHMENT, "", "c:/temp/image.jpg").
Option Declare
UseLSX "*javacon"
Use "GetImageFromUrl"
Sub Initialize
dim jSession As New JavaSession
dim jClass As JavaClass
Set jClass = jSession.GetClass( "GetImageFromUrl" )
If jClass.getImageFromUrl("https://your.url", "c:/temp/image.jpg") Then
MessageBox "File is downloaded"
End If
End Sub

Related

Java How to format URL as a String to connect with JSoup Malformed URL error

I have a program that connects to a user defined URL from a TextField and scrapes the images on that web page. The user defined URL is gotten from the textfield via .getText() and assigned to a String. The String is then used to connect to the Web page with JSoup and puts the webpage into a document.
String address = labelforAddress.getText();
try {
document = Jsoup.connect(address).get();
}catch(IOException ex){
ex.printStackTrace();
}
I've tried differently formatted URLS: "https://www.", "www.", "https://" but everything I use throws the malformed URL error.
Someone please show me how to get the text from the TextField the correct way.
Below is the entire code.
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main extends Application {
Document document;
LinkedList<String> imageURLList = new LinkedList<String>();
ArrayList<File> fileList = new ArrayList<File>();
int fileCount = 1;
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Webpage Photo Scraper");
GridPane gp = new GridPane();
Label labelforAddress = new Label("URL");
GridPane.setConstraints(labelforAddress, 0,0);
TextField URLAddress = new TextField();
GridPane.setConstraints(URLAddress, 1,0);
Button scrape = new Button("Scrape for Photos");
GridPane.setConstraints(scrape, 0,1);
scrape.setOnAction(event->{
String address = labelforAddress.getText();
try {
document = Jsoup.connect(address).get();
}catch(IOException ex){
ex.printStackTrace();
}
Elements imgTags = document.getElementsByAttributeValueContaining("src", "/CharacterImages");
for(Element imgTag: imgTags){
imageURLList.add(imgTag.absUrl("src"));
}
for(String url: imageURLList){
File file = new File("C:\\Users\\Andrei\\Documents\\file" + fileCount + ".txt");
downloadFromURL(url, file);
fileList.add(file);
fileCount++;
}
});
Button exportToZipFile = new Button("Export to Zip File");
GridPane.setConstraints(exportToZipFile, 0,2);
exportToZipFile.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter exfilt = new FileChooser.ExtensionFilter("Zip Files", ".zip");
fileChooser.getExtensionFilters().add(exfilt);
try{
FileOutputStream fos = new FileOutputStream(fileChooser.showSaveDialog(primaryStage));
ZipOutputStream zipOut = new ZipOutputStream(fos);
for(int count = 0; count<=fileList.size()-1; count++){
File fileToZip = new File(String.valueOf(fileList.get(count)));
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}catch(IOException e1){
e1.printStackTrace();
}
});
primaryStage.setScene(new Scene(gp, 300, 275));
primaryStage.show();
gp.getChildren().addAll(exportToZipFile, labelforAddress, scrape, URLAddress);
}
public static void downloadFromURL(String url, File file){
try {
URL Url = new URL(url);
BufferedInputStream bis = new BufferedInputStream(Url.openStream());
FileOutputStream fis = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
while((count = bis.read(buffer, 0,1024)) !=-1){
fis.write(buffer, 0, count);
}
fis.close();
bis.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Your text field containing the value entered by user is stored in URLAddress object but you always try to get the url from labelforAddress object which is a label always containing "URL" text.
So the solution is to use:
String address = URLAddress.getText();
If you read carefully error message it would help you to find the cause, because it always displays the value it considers wrong. In this case I see:
Caused by: java.net.MalformedURLException: no protocol: URL
and it shows the unrecognized address is: URL.
If you encounter this kind of error next time try:
debugging the aplication in runtime to see values of each variable
logging variable values in the console to see if variables contain values you expect

How read Chinese Characters from XLSX File? (Java)

I can already read in texts from xlsx cells and have:
String s = cell.getStringCellValue();
However when printing out this String, I get rubbish results. To solve this problem I used the Internet.
I tried about 8 different approaches and thus found that there is not yet a working answer on SO. I set the default encoding of my IDE and my XLSX Files to UTF-8. Pinyin can be correctly displayed.
Does anyone have an idea what could be wrong and how to solve this issue?
Not clear wherever your problem using chinese characters comes from, but I cannot reproduce it.
I have the following workbook in Excel:
The following simple code:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
class ReadXSSFUnicodeTest {
public static void main(String[] args) {
try {
Workbook wb = WorkbookFactory.create(new FileInputStream("ReadXSSFUnicodeTest.xlsx"));
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String string = cell.getStringCellValue();
System.out.println(string);
}
}
wb.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
produces:
If the problem is that Windows is not able displaying Unicode characters properly in CMD console because it has not a font with glyphs for it, then write the content to a text file:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
class ReadXSSFUnicodeTest {
public static void main(String[] args) {
try {
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ReadXSSFUnicodeTest.txt"), "UTF-8"));
Workbook wb = WorkbookFactory.create(new FileInputStream("ReadXSSFUnicodeTest.xlsx"));
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String string = cell.getStringCellValue();
out.write(string + "\r\n");
System.out.println(string);
}
}
out.close();
wb.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This file then should have proper content even in Windows Notepad:
You could also using Swing (JTextArea) to provide your own output area for test outputs:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import javax.swing.*;
import java.awt.*;
class ReadXSSFUnicodeTest {
public ReadXSSFUnicodeTest() {
try {
MySystemOut mySystemOut = new MySystemOut();
Workbook wb = WorkbookFactory.create(new FileInputStream("ReadXSSFUnicodeTest.xlsx"));
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String string = cell.getStringCellValue();
//System.out.println(string);
mySystemOut.println(string);
}
}
wb.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
ReadXSSFUnicodeTest readXSSFUnicodeTest= new ReadXSSFUnicodeTest();
}
private class MySystemOut extends JTextArea {
private String output = "";
private MySystemOut() {
super();
this.setLineWrap(true);
JFrame frame = new JFrame("My System Outputs");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane areaScrollPane = new JScrollPane(this);
areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(350, 150));
frame.getContentPane().add(areaScrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private void println(String output) {
this.output += output + "\r\n";
this.setText(this.output);
this.revalidate();
}
}
}
This is only the simplest way and only to get test outputs since it uses Swing not the right way in terms of AWT threading issues.
I had the same problem while extracting Persian text from an Excel file.
I was using ECLIPSE and change settings like:
Window -> Preferences -> Expand General and
Click Workspace, text file encoding (near bottom) has an encoding chooser.
Select "Other" radio button -> Select UTF-8 from the drop down.
Click Apply and OK button OR click simply OK button
use this Code:
String new_Str = new String(excelfield.getBytes(1), "Cp1256"); //....to Persian text
String new_Str = new String(excelfield.getBytes(1), "UTF-8"); //....to Chinese text
OR
String new_Str = new String(your_str.getBytes(), "Cp1256");
String new_Str = new String(your_str.getBytes(), "UTF-8");

Error while downloading & saving image to sd card in blackberry?

I am working on blackberry project where i want to download image & save it in sd card in blackberry. By going through many sites i got some code & based on that i wrote the program but when it is executed the output screen is displaying a blank page with out any response. The code i am following is..
code:
public class BitmapDemo extends UiApplication
{
public static void main(String[] args)
{
BitmapDemo app = new BitmapDemo();
app.enterEventDispatcher();
}
public BitmapDemo()
{
pushScreen(new BitmapDemoScreen());
}
static class BitmapDemoScreen extends MainScreen
{
private static final String LABEL_X = " x ";
BitmapDemoScreen()
{
//BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
//add(bmpFld1);
setTitle("Bitmap Demo");
// method for saving image in sd card
copyFile();
// Add a menu item to display an animation in a popup screen
MenuItem showAnimation = new MenuItem(new StringProvider("Show Animation"), 0x230010, 0);
showAnimation.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
// Create an EncodedImage object to contain an animated
// gif resource.
EncodedImage encodedImage = EncodedImage.getEncodedImageResource("animation.gif");
// Create a BitmapField to contain the animation
BitmapField bitmapFieldAnimation = new BitmapField();
bitmapFieldAnimation.setImage(encodedImage);
// Push a popup screen containing the BitmapField onto the
// display stack.
UiApplication.getUiApplication().pushScreen(new BitmapDemoPopup(bitmapFieldAnimation));
}
}));
addMenuItem(showAnimation);
}
private static class BitmapDemoPopup extends PopupScreen
{
public BitmapDemoPopup(BitmapField bitmapField)
{
super(new VerticalFieldManager());
add(bitmapField);
}
protected boolean keyChar(char c, int status, int time)
{
if(c == Characters.ESCAPE)
{
close();
}
return super.keyChar(c, status, time);
}
}
}
public static Bitmap connectServerForImage(String url) {
System.out.println("image url is:"+url);
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
public static void copyFile() {
// TODO Auto-generated method stub
EncodedImage encImage = EncodedImage.getEncodedImageResource("rim.png");
byte[] image = encImage.getData();
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(image);
outStream.close();
fc.close();
System.out.println("image saved.....");
} catch (Exception e) {
// TODO: handle exception
//System.out.println("exception is "+ e);
}
}
}
This is the code which i am using. Not getting any response except blank page.. As i am new to blackberry development unable to find out what is the problem with my code. Can anyone please help me with this...... Actually i am having other doubt as like android & iphone does in blackberry simulator supports for SD card otherwise we need to add any SD card slots for this externally...
Waiting for your reply.....
To simply download and save that image to the SDCard, you can use this code. I changed your SDCard path to use the pictures folder, which I think is the standard location on BlackBerrys. If you really want to store it in images, you may just need to create the folder if it doesn't already exist.
package com.mycompany;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
public class DownloadHelper implements Runnable {
private String _url;
public DownloadHelper(String url) {
_url = url;
}
public void run() {
HttpConnection connection = null;
OutputStream output = null;
InputStream input = null;
try {
// Open a HTTP connection to the webserver
connection = (HttpConnection) Connector.open(_url);
// Getting the response code will open the connection, send the request,
// and read the HTTP response headers. The headers are stored until requested.
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
input = new DataInputStream(connection.openInputStream());
int len = (int) connection.getLength(); // Get the content length
if (len > 0) {
// Save the download as a local file, named the same as in the URL
String filename = _url.substring(_url.lastIndexOf('/') + 1);
FileConnection outputFile = (FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/" + filename,
Connector.READ_WRITE);
if (!outputFile.exists()) {
outputFile.create();
}
// This is probably not a robust check ...
if (len <= outputFile.availableSize()) {
output = outputFile.openDataOutputStream();
// We'll read and write this many bytes at a time until complete
int maxRead = 1024;
byte[] buffer = new byte[maxRead];
int bytesRead;
for (;;) {
bytesRead = input.read(buffer);
if (bytesRead <= 0) {
break;
}
output.write(buffer, 0, bytesRead);
}
output.close();
}
}
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (connection != null) {
connection.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
// do nothing
}
}
}
}
This class can download an image in the background, as I suggested. To use it, you can start a worker thread like this:
DownloadHelper downloader = new DownloadHelper("http://images03.olx.in/ui/3/20/99/45761199_1.jpg");
Thread worker = new Thread(downloader);
worker.start();
This will save the file as /SDCard/BlackBerry/pictures/45761199_1.jpg. I tested it on a 5.0 Storm simulator.
There are several problems with the code posted. It's also not completely clear what you're trying to do. From the question title, I assume you want to download a jpg image from the internet, and display it.
1) You implement a method called connectServerForImage() to download an image, but then it's commented out. So, the method isn't going to download anything if it's not called.
2) Even if it's uncommented, connectServerForImage() is called here
BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
This will block the main (UI) thread while it downloads your image. Even though you can do it this way, it's not a good thing to do. Instead, you could create a Thread to download the image as a background task, and then use UiApplication.invokeLater() to load the image into your BitmapField on the main/UI thread.
3) Your copyFile() method tries to copy a file named rim.png, which must be an image bundled with your application, and saves it to the SDCard. Is this really what you want? Do you want to save the downloaded image instead? This method doesn't seem to be connected to anything else. It's not saving the image downloaded from the internet, and the image it does save is never used anywhere else.
4) In copyFile(), this line
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
is passing a byte[] in as part of the filename to open (your variable named image). You should probably be adding a String name to the end of your SDCard path. As the code is, it's probably opening a file in the /SDCard/BlackBerry/images/ folder with a very long name that looks like a number. Or it might fail entirely, if there are limits on the length of filenames.
5) In Java, it's not usually a good idea to make everything static. Static should normally be used for constants, and for a very few methods like the main() method, which must be static.
Try to clean these things up, and then repost the code, and we can try to help you with your problem. Thanks.

how to download file from server & save it to device using using blackberry api

I want to download a .txt file from http server and store it on device memory.How can i do it.I am new to it so any help would be appreciated. Thanks in advance
I am not going to code for you, But i can give you logic for it, as i have already done this kind of work.
You are going to need HttpConnection, DataInutStream,DataOutputStream and FileConnection Class for the same purpose.
Here is a link of an example, it is same as your question's requirement, you need to study it and code for your self.
Hint: Only minor changes require in that code, if you can figure it out.
Use the below code
package com.neel.java.rim.api.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.ui.component.Dialog;
public class FileDownloader implements Runnable {
// Holds the URL to download the file
StringBuffer url = null;
//holds the instance of the delegate screen
protected Object delegate;
public FileDownloader(String url) {
// image URL
this.url = new StringBuffer();
this.url.append(url.toString());
}
//taking the instance of the delegate
//this is the object of the active screen from where the request is made
public Object getDelegate() {
return delegate;
}
public void setDelegate(Object delegate) {
this.delegate = delegate;
}
// Thread starts the execution
public void run() {
byte[] dataArray;
InputStream input;
//url.append(updateConnSuffix()); // ad connection suffix for the data usage
HttpConnection httpConn = null;
try {
httpConn = (HttpConnection) Connector.open(url.toString());
input = httpConn.openInputStream();
dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);
writeFile(dataArray);
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("Eoor in downloading image");
}
}
public void writeFile(byte[] data){
FileConnection fc = null;
// to save in SD Card
String pFilePath = "SDCard/BlackBerry/pictures/text.txt";
/*use below path for saving in Device Memory*/
//String pFilePath = "store/home/user/pictures/text.txt";
OutputStream lStream = null;
String time = new String();
if (pFilePath != null) {
try {
fc = (FileConnection)Connector.open("file:///" + pFilePath ,Connector.READ_WRITE);
if(null == fc || fc.exists() == false){
fc.create();
}
lStream = fc.openOutputStream(fc.fileSize());
lStream.write(data);
} catch (Exception ioex) {
ioex.printStackTrace();
} finally {
if (lStream != null) {
try {
lStream.close();
lStream = null;
} catch (Exception ioex){
}
}
if (fc != null) {
try {
fc.close();
fc = null;
} catch (Exception ioex){
}
}
}
}
}
}

How to send audio data from Java Applet to Rails controller

I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save.
So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR :
LAVF_header: av_open_input_stream() failed
while playing with the mplayer.
Here is the sample Java Code i m using in which i m reading audio data from the audio file:
package networksocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager;
import sun.awt.HorizBagLayout;
import sun.awt.VerticalBagLayout;
import sun.misc.BASE64Encoder;
/**
*
* #author mukand
*/
public class Urlconnection extends JApplet implements ActionListener
{
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public BufferedInputStream in;
public BufferedOutputStream out;
public String line;
public FileOutputStream file;
public int bytesread;
public int toread=1024;
byte b[]= new byte[toread];
public String f="FINISH";
public String match;
public File fileopen;
public JTextArea jTextArea;
public Button refreshButton;
public HttpURLConnection urlConn;
public URL url;
OutputStreamWriter wr;
BufferedReader rd;
#Override
public void init() {
// TODO start asynchronous download of heavy resources
//textField= new TextField("START");
//getContentPane().add(textField);
JPanel p = new JPanel();
jTextArea= new JTextArea(1500,1500);
p.setLayout(new GridLayout(1,1, 1,1));
p.add(new JLabel("Server Details"));
p.add(jTextArea);
Container content = getContentPane();
content.setLayout(new GridBagLayout()); // Used to center the panel
content.add(p);
jTextArea.setLineWrap(true);
refreshButton = new java.awt.Button("Refresh");
refreshButton.reshape(287,49,71,23);
refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12));
refreshButton.addActionListener(this);
add(refreshButton);
Properties properties = System.getProperties();
properties.put("http.proxyHost", "netmon.iitb.ac.in");
properties.put("http.proxyPort", "80");
}
#Override
public void actionPerformed(ActionEvent e)
{
try
{
url = new URL("http://localhost:3000/audio/audiorecieve");
urlConn = (HttpURLConnection)url.openConnection();
//String login = "mukandagarwal:rammstein$";
//String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes());
//urlConn.setRequestProperty("Proxy-Authorization",login);
urlConn.setRequestMethod("POST");
// urlConn.setRequestProperty("Content-Type",
//"application/octet-stream");
//urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Length", "" +
// Integer.toString(urlParameters.getBytes().length));
urlConn.setRequestProperty("Content-Language", "UTF-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
byte bread[]=new byte[2048];
int iread;
char c;
String data=URLEncoder.encode("key1", "UTF-8")+ "=";
//String data="key1=";
FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3");
while((iread=fileread.read(bread))!=-1)
{
//data+=(new String());
/*for(int i=0;i<iread;i++)
{
//c=(char)bread[i];
System.out.println(bread[i]);
}*/
data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));//
// data+=new String(bread,iread);
}
//urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length));
System.out.println(data);
//data+=URLEncoder.encode("mukand", "UTF-8");
//data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
//data="key1=";
wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream();
//if((iread=fileread.read(bread))!=-1)
// wr.write(bread,0,iread);
wr.write(data);
wr.flush();
fileread.close();
jTextArea.append("Send");
// Get the response
rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = rd.readLine()) != null) {
jTextArea.append(line);
}
wr.close();
rd.close();
//jTextArea.append("click");
}
catch (MalformedURLException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void start()
{
}
#Override
public void stop()
{
}
#Override
public void destroy()
{
}
// TODO overwrite start(), stop() and destroy() methods
}
Here is the Rails controller function for recieving:
def audiorecieve
puts "///////////////////////////////////////******RECIEVED*******////"
puts params[:key1]#+" "+params[:key2]
data=params[:key1]
#request.env('RAW_POST_DATA')
file=File.new("audiodata.ogg", 'w')
file.write(data)
file.flush
file.close
puts "////**************DONE***********//////////////////////"
end
Please reply quickly
Base64 encode the data. Send it as a string, receive it on the Rails side and decode it back to the original format.

Resources