Streaming picture from java to php? - java

I am taking screenshot of my desktop and i want to know how i would go if i want to send it to php site and then display it?
I have made this and no results about streaming.
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;
public class Stream{
static public void captureScreen() throws Exception {
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ImageIO.write(image, "png", buffer);
byte[] data = buffer.toByteArray();
try {
// open a connection to the site
URL url = new URL("http://futuretechs.eu/stream.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("image=" + encodeArray(data));
System.out.println(encodeArray(data));
// we have to get the input stream in order to actually send the request
con.getInputStream();
// close the print stream
ps.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try{
System.out.println("[ Stream Started ]");
while(true){
Thread.currentThread().sleep(100);
Stream.captureScreen();
}
// System.out.println("[ Stream Ended ]");
}
catch(Exception e)
{
e.printStackTrace();
}
}
static String encodeArray(byte[] in) throws IOException {
StringBuffer out = new StringBuffer();
out.append(Base64Coder.encode(in, 0, in.length));
return out.toString();
}
}
How now i would send from java the byte[] to php and play it?
So it would go like this
Java Client program sends to php site the byte[] content and then the php shows it to the user who is at the site?
Thank you!
EDIT: CODE UPDATED

What is that site you wanna upload the screenshot content? Is that site on the internet?
There are different approaches.
- You could have a php page which waits for an HTTP-POST request, with the screenshot in the payload, while the site itself has a php-module running on that server and gets invoked by the web-request.
- That server probably supports WebDav, then you could upload your screenshot via HTTP-PUT and invoke a php site with HTTP-GET (while sending the filename with your HTTP-GET-Args).
It's hard to tell, if we don't know the php-site, it's API and/or it's behaviour.

well its better to convert the image bytes into base64 before sending to php
when you send to php you can use this function imagecreatefromstring($image_data) to display
display.php
<?php
$image = $_POST['image'];
$data = base64_decode($image);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>
this should work with (PHP 4 >= 4.0.4, PHP 5)
Let me know if it works :)
Edit :
I am not really good with java try the below
As asked java code
try {
// open a connection to the site
URL url = new URL("http://www.yourdomain.com/yourphpscript.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("image=BASE64_ENCODED_STRING_HERE");
// we have to get the input stream in order to actually send the request
con.getInputStream();
// close the print stream
ps.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
or Use HTTP Client in java
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://www.yourdomain.com/yourphpscript.php");
method.addParamezter("image","BASE64_ENCODED_STRING"); // or whatever
int statusCode = client.executeMethod(method);

Related

Streaming Rest Api - Send data in chunks to the client in a stream from the restful api

I have a requirement where I have to create a streaming rest api to read a file. We are building something similar to cat linux command.
So in case if the user types in ccat filename | tail, then we have to keep the stream open and read out the content in chunks of 256 bytes and wait till the resource is closed from the client.
I have created a POC. The rest api code looks something like this -
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#RequestMapping(method = RequestMethod.GET, value = "stream")
public void hello(#Context HttpServletRequest request, #Context HttpServletResponse response)
throws InterruptedException {
String content = "This is the text content";
ServletOutputStream outputStream = null;
try {
for(int i=0;i<100;i++){
content = content + i;
final byte[] bytes = content.getBytes();
outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setStatus(200);
outputStream.write(bytes);
Thread.sleep(1000l);
outputStream.flush();
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
And the client code is as follows -
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:6868/api/stream");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn);
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is working fine, but the problem is it is not writing the chunks of bytes, rather the entire content in one go. I am calling flush() so I was expecting that it will send the chunks to the client on each call of flush() but that doesn't seem to be happening. It is sending to the client after the call to the close(). How can I fix this?
I think it will be better to use java sockets for this use case.

Can't download file from internet using java

I'm trying to download file from internet using java but there have a problem. I'm not failed but each time when I'm trying to download it's downloading only 250-300 KB only though the file size is larger than that. I have tried a lot of ways but every time the result is same.
I have tried Apache Commons IO like this,
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
try {
String from = "https://download.gimp.org/mirror/pub/gimp/v2.8/gimp-2.8.10.tar.bz2";
String to = "/home/ashik/gimp-2.8.10.tar.bz2";
System.out.println("Starting!");
FileUtils.copyURLToFile(new URL(from), new File(to), Integer.MAX_VALUE, Integer.MAX_VALUE);
System.out.println("Finished!");
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
I have tried Java NIO like this,
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class Main {
public static void main(String[] args) {
try {
String from = "https://download.gimp.org/mirror/pub/gimp/v2.8/gimp-2.8.10.tar.bz2";
String to = "/home/ashik/gimp-2.8.10.tar.bz2";
System.out.println("Starting!");
ReadableByteChannel rbc = Channels.newChannel(new URL(from).openStream());
FileOutputStream fos = new FileOutputStream(to);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
System.out.println("Finished!");
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
I have also followed some stackoverflow solutions like, How to download and save a file from Internet using Java? , How to download large sized Files (size > 50MB) in java, etc but none of them are working.
Every time it's downloading but file size is only 250-300 KB. How to solve this problem?
Platform:
OS: Debian-9
JDK-Version: Oracle JDK-9
IDE: Eclipse Oxygen
Thank you in advance.
You don’t need a third-party library to do this. You could use Channels, but it’s shorter to use Files.copy:
try (InputStream stream = new URL(from).openStream()) {
Files.copy(stream, Paths.get(to));
}
In your case, the URL is redirecting to a different location. Ordinarily, calling setInstanceFollowRedirects would be sufficient:
HttpURLConnection conn = new URL(from).openConnection();
conn.setInstanceFollowRedirects(true);
try (InputStream stream = conn.getInputStream()) {
Files.copy(stream, Paths.get(to));
}
However, this is a special case. Your URL is an https URL, which redirects to an http URL.
Java considers that insecure (as it should), so it will never automatically follow that redirect, even if setInstanceFollowRedirects has been called.
Which means you have to follow the redirects yourself:
URL url = new URL(from);
HttpURLConnection conn;
while (true) {
conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);
int responseCode = conn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_MOVED_PERM &&
responseCode != HttpURLConnection.HTTP_MOVED_TEMP &&
responseCode != 307) {
break;
}
url = new URL(conn.getHeaderField("Location"));
}
try (InputStream stream = conn.getInputStream()) {
Files.copy(stream, Paths.get(to));
}

Java - writing to url not working

I'm trying to make a java program that changes a text document on my website. The permissions are on that everyone can edit it. I've tried, and reading it works perfectly, but writing doesn't.
Here's the code for the writing:
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
URL infoThing = new URL("http://www.[name of my website]/infoThing.txt");
URLConnection con = infoThing.openConnection();
con.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write("Change to this.");
out.close();
}
}
For a Java program to interact with a server-side process it simply must be able to write to a URL, thus providing data to the server. It can do this by following these steps:
1 Create a URL.
2 Retrieve the URLConnection object.
3 Set output capability on the URLConnection.
4 Open a connection to the resource.
5 Get an output stream from the connection.
6 Write to the output stream.
7 Close the output stream.
If you want to write to the url. You have to use the concepts above and concepts for servlets.
An example program that runs the backwards script over the network through a URLConnection:
import java.io.*;
import java.net.*;
public class ReverseTest {
public static void main(String[] args) {
try {
if (args.length != 1) {
System.err.println("Usage: java ReverseTest string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[0]);
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection connection = url.openConnection();
PrintStream outStream = new PrintStream(connection.getOutputStream());
outStream.println("string=" + stringToReverse);
outStream.close();
DataInputStream inStream = new DataInputStream(connection.getInputStream());
String inputLine;
while ((inputLine = inStream.readLine()) != null) {
System.out.println(inputLine);
}
inStream.close();
} catch (MalformedURLException me) {
System.err.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
}
}
}

Connect to remote server with username/password for downloading files

I need to connect to a remote server which requires username/password and need to download videos and other pdf documents. What is the best way in java. A little code sample will be highly appreciable. I tried following, accept my apologies in advance if this code seems like a novice effort as I just started Java and learning the best practices from the guru's like you :). Problem is how to authenticate, how to provide username/password to the server.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Downloader {
URL url;
public Downloader(){
try {
url = new URL("https://d396qusza40orc.cloudfront.net/algs4partI/slides%2F13StacksAndQueues.pdf");
try {
URLConnection con = url.openConnection();
con.connect();
InputStream inStream = url.openStream();
FileOutputStream outStream = new FileOutputStream("data.dat");
int bytesRead;
byte[] buffer = new byte[100000];
while((bytesRead = inStream.read(buffer)) > 0){
outStream.write(buffer, 0 , bytesRead);
buffer = new byte[100000];
}
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
Downloader d = new Downloader();
}
}
You should be able to provide the username/password as part of the URL:
E.g.
https://username:password#example.com/secure/myfile.pdf
This does assume that the site is using standard HTTP authentication.
If some sort of custom authentication is being done you may need to supply a per-generated cookie containing authentication information or possibly do a separate log-in request before trying to download your file. This will all depend on the setup of the remote server.

Check if URL is valid or exists in java

I'm writing a Java program which hits a list of urls and needs to first know if the url exists. I don't know how to go about this and cant find the java code to use.
The URL is like this:
http: //ip:port/URI?Attribute=x&attribute2=y
These are URLs on our internal network that would return an XML if valid.
Can anyone suggest some code?
You could just use httpURLConnection. If it is not valid you won't get anything back.
HttpURLConnection connection = null;
try{
URL myurl = new URL("http://www.myURL.com");
connection = (HttpURLConnection) myurl.openConnection();
//Set request to header to reduce load as Subirkumarsao said.
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
} catch {
//Handle invalid URL
}
Or you could ping it like you would from CMD and record the response.
String myurl = "google.com"
String ping = "ping " + myurl
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(ping);
r.exec(ping);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inLine;
BufferedWriter write = new BufferedWriter(new FileWriter("C:\\myfile.txt"));
while ((inLine = in.readLine()) != null) {
write.write(inLine);
write.newLine();
}
write.flush();
write.close();
in.close();
} catch (Exception ex) {
//Code here for what you want to do with invalid URLs
}
}
A malformed url will give you an exception.
To know if you the url is active or not you have to hit the url. There is no other way.
You can reduce the load by requesting for a header from the url.
package com.my;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
public class StrTest {
public static void main(String[] args) throws IOException {
try {
URL url = new URL("http://www.yaoo.coi");
InputStream i = null;
try {
i = url.openStream();
} catch (UnknownHostException ex) {
System.out.println("THIS URL IS NOT VALID");
}
if (i != null) {
System.out.println("Its working");
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
output : THIS URL IS NOT VALID
Open a connection and check if the response contains valid XML? Was that too obvious or do you look for some other magic?
You may want to use HttpURLConnection and check for error status:
HttpURLConnection javadoc

Categories

Resources