So I am new to java programming and I am supposed to download data from the URL below every 5 minute.
host: 204.8.38.210
Get:/Iowa.Sims.AllSites.C2C/IADOT_SIMS_AllSites_C2C.asmx/OP_ShareTrafficDetectorData?MSG_TrafficDetectorDataRequest=string%20HTTP/1.1
I get this error-"Server returned HTTP response code : 400 " using this code below
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class JavaDownload {
public static void main(String[] args) throws IOException{
String fileName = "file3x.html";
URL link = new URL("http://204.8.38.210/Iowa.Sims.AllSites.C2C/IADOT_SIMS_AllSites_C2C.asmx/OP_ShareTrafficDetectorData?MSG_TrafficDetectorDataRequest=string%20HTTP/1.1");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while(-1!=(n=in.read(buf)))
{
out.write(buf,0,n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
System.out.println("Finished");
}
}
Related
I would SEND " filename" and "file " through socket , I was able to easily send the file but when I try to send strings eg PrintWriter pw.println ( ) or DataOutputStream or " out.writeUTF ( ) " the file is sent corrupt, I read a lot of questions on StackOverflow but have not found the answer , I'm looking for some example to send strings and files , can you help ?
server
package serverprova;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ServerProva {
final static int porta=8888;//porta server dove si collegano i client
public static void main(String[] args) throws IOException {
// TODO code application logic here
ServerSocket serverSocket=null;
boolean ascoltando=true;
serverSocket = new ServerSocket(porta);//avvia il server con il numero di porta
Socket s;
BufferedReader br1=null;
// ****** interfaccia f=new interfaccia);
boolean r=true;
BufferedInputStream bis=null;
Scanner sc;
FileOutputStream fout;
while(ascoltando)
{
s=serverSocket.accept();// this socket
String filename="";
String nome_cartella="";
InputStream in = null;
OutputStream out = null;
DataInputStream inString;
inString = new DataInputStream(new BufferedInputStream(s.getInputStream()));
// filename = inString.readUTF();
// nome_cartella = inString.readUTF();
in = s.getInputStream();
//out = new FileOutputStream(nome_cartella+"/"+filename);
out = new FileOutputStream("ciao"+"/"+"asd.jpg");
byte[] b = new byte[20*1024];
int i ;
while((i = in.read(b)) >0){
out.write(b, 0, i);
}
out.close();
in.close();
//inString.close();
s.close();
}
}
}
client
package clientprova;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class ClientProva {
final static int porta=8888;
public static void main(String[] args) throws FileNotFoundException, IOException {
File file;
file = new File("kirlian12.jpg");
InetAddress host = InetAddress.getLocalHost();
Socket sock = new Socket(host.getHostName(), 8888);
DataOutputStream outString = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
// outString.writeUTF(file.getName());
// outString.writeUTF("rivelatore2");
// outString.flush();
byte[] b = new byte[20*1024];
InputStream in = new FileInputStream(file);
OutputStream out = sock.getOutputStream();
int i ;
while ((i = in.read(b)) >0 ) {
out.write( b , 0 , i);
}
out.close();
in.close();
sock.close();
}
}
when I try to uncomment the commented lines , my files get corrupted
When you wrap InputStream with BufferedInputStream, the latter "takes ownership" of InputStream. This means that when you call readUtf(), BufferedInputStream may read more bytes from InputStream than it is necessary for reading UTF string. So, when you next access InputStream directly, some part of transferred file is missing (because it was previously read into BufferedInputStream's buffer and currently resides there).
inString = new DataInputStream(new BufferedInputStream(s.getInputStream()));
filename = inString.readUTF();
nome_cartella = inString.readUTF();
...
in = s.getInputStream();
while((i = in.read(b)) >0){
You must choose from two alternatives: either to always use raw InputStream OR to always use BufferedInputStream. The same reasoning works also for OutputStream (but you managed to avoid problem by calling flush()).
I am creating a simple application thats uploads and downloads files to/from a server.
For testing purposes I am using localhost for testing. I am looking for a simple way to download a file from the browser in Java.
Here is a code to download files from a web site in Java ... You can adapt this
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class DownloadFile {
public static void main(String[] args) throws IOException {
String fileName = "fileName.txt";
URL link = new URL("http://websiteToDownloadFrom.com");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
}
}
If it is in localhost:
url = new URL("http://localhost:8052/directoryPath/fileName.pdf");
I need to read an image file and send it to a web browser using HTTP protocol, and I cannot figure out how to send the bytes of the image. I cannot for the life of me figure it out. Thanks in advance. Here is my code:
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Main {
byte[] byt=null;
public String read(String message){
String httpHeader="";
String toReturn="";
try{
if(message!=null){
String[] parts=message.split("\n");
String[] RequstParts=parts[0].split(" ");
System.out.println("This is a "+RequstParts[0]+" request for "+RequstParts[1]);
if(RequstParts[1].equals("/"))RequstParts[1]="index.html";
if(RequstParts[0].equals("GET")){
if(RequstParts[1].endsWith(".html")){
httpHeader="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
BufferedReader in = new BufferedReader(new FileReader(new File("WebContent/"+RequstParts[1])));
String line="";
while(null!=(line=in.readLine())){
toReturn+=line;
}
}else if(RequstParts[1].endsWith(".jpg")){
httpHeader="HTTP/1.1 200 OK\r\nContent-Type: image/jpg\r\nContent-Length: 13312\r\n\r\n";
}
}
}
}catch(Exception e){
toReturn+="<br>ERROR: "+e.toString();
return httpHeader+toReturn;
}
return httpHeader+toReturn;
}
public Main(){
try{
ServerSocket listener = new ServerSocket(9090);
System.out.println("HTTP server started!");
while(true){
Socket socket = listener.accept();
System.out.println("\nRecieved Data!");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message=read(in.readLine());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("\nSENDING "+message);
out.println(message);
out.println(byt);
out.close();
}
}catch(Exception e){
System.out.println("ERROR "+e.toString());
e.printStackTrace();
}
}
public static void main(String args[]){
new Main();
}
}
This should work:
public byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
So call this extractBytes on an image (specified as a filename to the method here), and send the returned byte[] using:
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(byte[]);
Method code taken from here.
I want to send an image from java websocket server to HTML5 page. When I try to send String client received correct information, but when I want to send image in byteArray i get error:
"WebSocket connection to 'ws://127.0.0.1:9000/' failed: Unrecognized frame opcode: 15"
My server code:
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
public class WebSocket {
private ServerSocket server;
private Socket sock;
private InputStream in;
private OutputStream out;
public WebSocket() {
}
public void listen(int port) throws IOException {
server = new ServerSocket(port);
sock = server.accept();
server.close();
in = sock.getInputStream();
out = sock.getOutputStream();
}
private void handshake() throws Exception {
BufferedReader br = new BufferedReader(
new InputStreamReader(in, "UTF8"));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "UTF8"));
// the first line of HTTP headers
String line = br.readLine();
if (!line.startsWith("GET"))
throw new IOException("Wrong header: " + line);
// we read header fields
String key = null;
// read line by line until we get empty line
while (!(line = br.readLine()).isEmpty()) {
if (line.toLowerCase().contains("sec-websocket-key")) {
key = line.substring(line.indexOf(":") + 1).trim();
}
}
if (key == null)
throw new IOException("No Websocket key specified");
System.out.println(key);
// add key and magic value
String accept = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// sha1
byte[] digest = MessageDigest.getInstance("SHA-1").digest(
accept.getBytes("UTF8"));
// and base64
accept = DatatypeConverter.printBase64Binary(digest);
// send http headers
pw.println("HTTP/1.1 101 Switching Protocols");
pw.println("Upgrade: websocket");
pw.println("Connection: Upgrade");
pw.println("Sec-WebSocket-Accept: " + accept);
pw.println();
pw.flush();
}
private void send(String message) throws Exception {
BufferedImage image = ImageIO.read(new File("image.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] byteArray = baos.toByteArray();
out.write(byteArray);
out.flush();
}
private void close() {
try {
sock.close();
} catch (IOException e) {
System.err.println(e);
}
}
/** throws Exception, because we don't really care much in this example */
public static void main(String[] args) throws Exception {
WebSocket ws = new WebSocket();
System.out.println("Listening...");
ws.listen(9000);
System.out.println("Handshake");
ws.handshake();
System.out.println("Handshake complete!");
ws.send("I got your message! It's length was");
ws.close();
}
}
and my page in html:
<!DOCTYPE HTML>
<html>
<body>
<button onclick="webs()">WebSocket message</button>
<script>
function webs() {
var ws = new WebSocket("ws://127.0.0.1:9000");
ws.onopen = function(){
console.log("Opened!");
};
ws.onmessage = function(evt){
console.log("Received!");
};
ws.onclose = function(ev){
console.log("Closing connection");
};
ws.onerror = function(ev){
console.log("Connection error: " + ev.reason);
};
}
</script>
</body>
</html>
I quess it is something wrong with this handshake and http headers but I have no idead what.
i think u miss "\r\n" at the end of each line
check this
http://en.wikipedia.org/wiki/WebSocket
hope this helps ..
I am reading a video file data in bytes and sending to another file but the received video file is not playing properly and is chattered.
Can anyone explain me why this is happening and a solution is appreciated.
My code is as follows
import java.io.*;
public class convert {
public static void main(String[] args) {
//create file object
File file = new File("B:/music/Billa.mp4");
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//create string from byte array
String strFileContent = new String(fileContent);
System.out.println("File content : ");
System.out.println(strFileContent);
File dest=new File("B://music//a.mp4");
BufferedWriter bw=new BufferedWriter(new FileWriter(dest));
bw.write(strFileContent+"\n");
bw.flush();
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
}
}
This question might be dead but someone might find this useful.
You can't handle video as string. This is the correct way to read and write (copy) any file using Java 7 or higher.
Please note that size of buffer is processor-dependent and usually should be a power of 2. See this answer for more details.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String args[]) {
final int BUFFERSIZE = 4 * 1024;
String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";
try(
FileInputStream fin = new FileInputStream(new File(sourceFilePath));
FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
){
byte[] buffer = new byte[BUFFERSIZE];
while(fin.available() != 0) {
bytesRead = fin.read(buffer);
fout.write(buffer, 0, bytesRead);
}
}
catch(Exception e) {
System.out.println("Something went wrong! Reason: " + e.getMessage());
}
}
}
Hope this also helpful for you - This can read and write a file into another file (You can use any file type to do that)
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Copy {
public static void main(String[] args) throws Exception {
FileInputStream input = new FileInputStream("input.mp4"); //input file
byte[] data = input.readAllBytes();
FileOutputStream output = new FileOutputStream("output.mp4"); //output file
output.write(data);
output.close();
}
}
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import javax.imageio.ImageIO;
public class Reader {
public Reader() throws Exception{
File file = new File("C:/Users/Digilog/Downloads/Test.mp4");
FileInputStream fin = new FileInputStream(file);
byte b[] = new byte[(int)file.length()];
fin.read(b);
File nf = new File("D:/K.mp4");
FileOutputStream fw = new FileOutputStream(nf);
fw.write(b);
fw.flush();
fw.close();
}
}
In addition to Jakub Orsula's answer, one needs to check the result of read operation to prevent garbage being written to end of file in last iteration.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String args[]) {
final int BUFFERSIZE = 4 * 1024;
String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";
try(
FileInputStream fin = new FileInputStream(new File(sourceFilePath));
FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
){
byte[] buffer = new byte[BUFFERSIZE];
int bytesRead;
while(fin.available() != 0) {
bytesRead = fin.read(buffer);
fout.write(buffer, 0, bytesRead);
}
}
catch(Exception e) {
System.out.println("Something went wrong! Reason: " + e.getMessage());
}
}
}