map file directory from a java server to local machine - java

I have created a java server application which will take GET requests and return files to the browser. Also the files are downloaded to the directory using "content-disposition:attachment" in header.But this only downloads as files, I want to download as a folder and map it to a local directory. for example
localhost:8080/xyz.jpg gives u an image .But localhost:8080/src/xyz.jpg should be downlaoded as src folder with an image in it eg: downloads/src/xyz.jpg. Currently if i do that ,it downloads as just a file. Since you guys asked.Here is the example code i used :) .thanks
import java.io.*;
import java.net.*;
import java.util.*;
public class myHTTPServer extends Thread {
static final String HTML_START =
"<html>" +
"<title>HTTP Server in java</title>" +
"<body>";
static final String HTML_END =
"</body>" +
"</html>";
Socket connectedClient = null;
BufferedReader inFromClient = null;
DataOutputStream outToClient = null;
public myHTTPServer(Socket client) {
connectedClient = client;
}
public void run() {
try {
System.out.println( "The Client "+
connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");
inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
responseBuffer.append("The HTTP Client request is ....<BR>");
System.out.println("The HTTP request string is ....");
while (inFromClient.ready())
{
// Read the HTTP complete HTTP Query
responseBuffer.append(requestString + "<BR>");
System.out.println(requestString);
requestString = inFromClient.readLine();
}
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {
// The default home page
sendResponse(200, responseBuffer.toString(), false);
} else {
//This is interpreted as a file name
String fileName = httpQueryString.replaceFirst("/", "");
fileName = URLDecoder.decode(fileName);
if (new File(fileName).isFile()){
sendResponse(200, fileName, true);
}
else {
sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
}
}
}
else sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {
String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
String Content_disposition="Content-Disposition: attachment; filename='src/fname.ext'";
FileInputStream fin = null;
if (statusCode == 200)
statusLine = "HTTP/1.1 200 OK" + "\r\n";
else
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
if (isFile) {
fileName = responseString;
fin = new FileInputStream(fileName);
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
contentTypeLine = "Content-Type: \r\n";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.HTML_END;
contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
}
outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes(Content_disposition);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");
if (isFile) sendFile(fin, outToClient);
else outToClient.writeBytes(responseString);
outToClient.close();
}
public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
byte[] buffer = new byte[1024] ;
int bytesRead;
while ((bytesRead = fin.read(buffer)) != -1 ) {
out.write(buffer, 0, bytesRead);
}
fin.close();
}
public static void main (String args[]) throws Exception {
ServerSocket Server = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println ("TCPServer Waiting for client on port 5000");
while(true) {
Socket connected = Server.accept();
(new myHTTPServer(connected)).start();
}
}
}

You can't do this using the HTTP protocol and a normal browser, there is no MIME type for folders. Your browser is able to download only files.
If you want to do this through HTTP:
Option 1: Generate a "zip" file (or some other format that enables you to package a folder tree into a single file) which contains the folder tree and send that to the browser.
Option 2: Develop a custom client program that is able to interpret the response that it gets from the server and create the corresponding folders on the local filesystem.

Related

Getting the string values of an enum

I want to make a program that downloads some files that are needed to run a gain. It's like a launcher that automatically downloads updates. This is the enum I have:
public class Configuration {
public enum downloadFiles {
load1 ("load1.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load1.png"),
load2 ("load2.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load2.png"),
load3 ("load3.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load3.png");
public String fileName, URL;
private downloadFiles(String fileName, String URL) {
this.fileName = fileName;
this.URL = URL;
}
public String getFileName() {
return fileName;
}
public String getURL() {
return URL;
}
}
}
I also have a class that downloads the files, which is:
public class DownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileName, String fileURL)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = System.getProperty("user.home") + "/Desktop" + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
So what I want to do is that the downloadFiles method downloads all the files in the enum sequentially. Btw is this a good way of doing this? If there is a better way, can you please tell me, because I'm trying to learn to code java in a neat way.
You can do the following:
for(Configuration.downloadFiles df : Configuration.downloadFiles.values()){
DownloadUtility.downloadFile(df.getFileName(), df.getURL());
}

cache webpage using java proxy server

I'm trying to study client/server using java. Need you help guys. Thanks in advance.
I built a proxy server that connects to the browser, what I would like to do is when it connects to the browser it will cache or download the webpage that the browser visited. Is it possible? Any tips or materials you can suggest? if possible, a sample code would be perfect because I really don't have any idea on how to do it.
Here is my code for my proxy server.
import java.io.*;
import java.net.*;
import java.util.*;
public class test extends Thread {
Socket connectedClient = null;
BufferedReader inFromClient = null; // request from the client (browser)
DataOutputStream outToClient = null; // response to client (browser)
public test(Socket client) {
connectedClient = client;
}
public void run() {
try {
System.out.println( "The Client "+
connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");
inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("The HTTP Client request is ....<BR>");
System.out.println("The HTTP request string is ....");
while (inFromClient.ready())
{
// Read the HTTP complete HTTP Query
responseBuffer.append(requestString + "<BR>");
System.out.println(requestString);
requestString = inFromClient.readLine();
}
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {
// The default home page
httprequest(200, responseBuffer.toString());
} else {
//filename : request from the client
String fileName = httpQueryString;
fileName = URLDecoder.decode(fileName);
System.out.println("Request:" + fileName);
httprequest(200,fileName);
}
}
else httprequest(404, "<b>The Requested resource not found ....</b>");
} catch (Exception e) {
e.printStackTrace();
}
}
public void httprequest(int statusCode,String location) throws Exception {
HttpURLConnection connection = null;
StringBuilder sb = null;
String line = null;
URL serverAddress = null;
String statusLine = null;
String serverdetails = "Server: Java ProxyServer";
String contentTypeLine = "Content-type: text/html\n\n";
if (statusCode == 200)
{
statusLine = "HTTP/1.1 200 OK" + "\r\n";
try {
serverAddress = new URL(location);
connection = null;
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
//read the result from the server
InputStream rd = connection.getInputStream();
outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes("\r\n");
byte[] buffer = new byte[1024] ;
int bytesRead;
while ((bytesRead = rd.read(buffer)) != -1 ){
outToClient.write(buffer, 0, bytesRead);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
}
}
else{
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
}
outToClient.close();
}
public static void main (String args[]) throws Exception {
//System.setProperty("http.proxyHost","172.16.1.254") ;
// System.setProperty("http.proxyPort", "3128") ;
ServerSocket Server = new ServerSocket (8080, 0, InetAddress.getByName("localhost"));
System.out.println ("Proxy Server Waiting for client on port 8080");
while(true) {
Socket connected = Server.accept();
(new test(connected)).start();
}
}
}
I hope you want monitor HTTP trafic, Take a reference from this, http://www.java2s.com/Code/Java/Network-Protocol/Asimpleproxyserver.htm even I built by my own by taking references from this kinda resources. But SSL communication you cannot do monitoring.

How to upload large files by multipart request in Java?

I am using this tutorial to upload large files but it is unable to upload even 300KB of file. Also it does not upload anything other than *.txt or *.log files. Need pointers which can help me upload large files irrespective of filetypes.
Sharing modified code
public class MultipartUtility {
private final String boundary
private static final String LINE_FEED = "\r\n"
private HttpURLConnection httpConn
private String charset
private OutputStream outputStream
private PrintWriter writer
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "==="
URL url = new URL(requestURL)
httpConn = (HttpURLConnection) url.openConnection()
httpConn.setUseCaches(false)
httpConn.setDoOutput(true) // indicates POST method
httpConn.setDoInput(true)
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary)
httpConn.setRequestProperty("User-Agent", "CodeJava Agent")
httpConn.setRequestProperty("Test", "Bonjour")
outputStream = httpConn.getOutputStream()
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true)
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED)
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED)
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED)
writer.append(LINE_FEED)
writer.append(value).append(LINE_FEED)
writer.flush()
}
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName()
writer.append("--" + boundary).append(LINE_FEED)
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED)
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED)
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED)
writer.append(LINE_FEED)
writer.flush()
FileInputStream inputStream = new FileInputStream(uploadFile)
byte[] buffer = new byte[4096]
int bytesRead = -1
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead)
}
outputStream.flush()
inputStream.close()
writer.append(LINE_FEED)
writer.flush()
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED)
writer.flush()
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>()
writer.append(LINE_FEED).flush()
writer.append("--" + boundary + "--").append(LINE_FEED)
writer.close()
// checks server's status code first
int status = httpConn.getResponseCode() //<- Exception coming in this line java.io.IOException: Error writing to server
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()))
String line = null
while ((line = reader.readLine()) != null) {
response.add(line)
}
reader.close()
httpConn.disconnect()
} else {
throw new IOException("Server returned non-OK status: " + status)
}
return response
}
static main(args) {
String charset = "UTF-8";
File uploadFile1 = new File("C:\\1392943434245.xml");
String requestURL = "http://localhost:10060/testme";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Have you checked that your HTTP server does not impose a size limit on requests ?
Is there enough memory and disk size ?
Maybe the cause is not in your code.
Try this code, you can be able to upload any file type
public class TryFile {
public static void main(String[] ar) throws HttpException, IOException, URISyntaxException {
// TODO Auto-generated method stub
TryFile t=new TryFile();
t.method();
}
public void method() throws HttpException, IOException, URISyntaxException
{
String url="<your url>";
String fileName="<your file name>";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
System.out.println("post length"+reqEntity.getContentLength());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("end"+resEntity.getContentLength());
}
}
This is a working code for file upload:
<jsp:useBean id="upBean" scope="session" class="javazoom.upload.UploadBean" >
<jsp:setProperty name="upBean" property="filesizelimit" value="<%= 1024 * 1024%>" />
</jsp:useBean>
try this,
try {
if (MultipartFormDataRequest.isMultipartFormData(request)) {
MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
Hashtable files = mrequest.getFiles();
byte data[] = null;
if ((files != null) && (!files.isEmpty())) {
fileObj = (UploadFile) files.get("fileUpload");
m_imagename = fileObj.getFileName().trim();
//File type validator
if (!Utility.isValiedFileName1(m_imagename)) {
ERROR = "Invalid File Type";
response.sendRedirect("XXX.jsp");//response page
return;
}
//file uploader method call
if ((fileObj != null) && (fileObj.getFileName() != null)) {
data = fileObj.getData();
//Java method for uploading
result = imageUpload.copyImage(data);//depCode
}
}
}
} catch (Exception e) {
SystemMessage.getInstance().writeMessage(" ERROR : " + e);
}
This is part related to HTTP.
Refer
here
We can upload any number of files of any sizes using plupload.

Java Server: Socket sending HTML code to browser

I am trying to write a simple Java program using ServerSockets that will send some HTML code to the browser. Here is my code:
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(55555);
} catch (IOException e) {
System.err.println("Could not listen on port: 55555.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
if(clientSocket != null) {
System.out.println("Connected");
}
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("\r\n");
out.println("<p> Hello world </p>");
out.flush();
out.close();
clientSocket.close();
serverSocket.close();
I then go to localhost:55555 in my browser and nothing displays. I know the connection is working because the program outputs "Connected" as checked in the if statement. I have also tried outputting the data from the inputStream and that works. But the text I am trying to output in the browser is not displaying at all, the program finishes running and I get a
"Problem loading page - the connection has been reset"
in my browser, but no text.
I have searched the internet and it seems everyone else coding it this way is having their text display fine, they are having other problems.
How can I fix this?
I tested your code in Chrome, Firefox, IE, and Opera and it works.
However, I would suggest that you use multi-threading and essentially spawn a new thread to handle each new request.
You can create a class that implements runnable and takes a clientSocket within the constructor. This will essentially make your custom webserver capable of accepting more than one request concurrently.
You will also need a while loop if you want to handle more than one total requests.
A good read demonstrating the above: https://web.archive.org/web/20130525092305/http://www.prasannatech.net/2008/10/simple-http-server-java.html
If the web-archive is not working, I'm posting the code below (taken from above):
/*
* myHTTPServer.java
* Author: S.Prasanna
* #version 1.00
*/
import java.io.*;
import java.net.*;
import java.util.*;
public class myHTTPServer extends Thread {
static final String HTML_START =
"<html>" +
"<title>HTTP Server in java</title>" +
"<body>";
static final String HTML_END =
"</body>" +
"</html>";
Socket connectedClient = null;
BufferedReader inFromClient = null;
DataOutputStream outToClient = null;
public myHTTPServer(Socket client) {
connectedClient = client;
}
public void run() {
try {
System.out.println( "The Client "+
connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");
inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
responseBuffer.append("The HTTP Client request is ....<BR>");
System.out.println("The HTTP request string is ....");
while (inFromClient.ready())
{
// Read the HTTP complete HTTP Query
responseBuffer.append(requestString + "<BR>");
System.out.println(requestString);
requestString = inFromClient.readLine();
}
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {
// The default home page
sendResponse(200, responseBuffer.toString(), false);
} else {
//This is interpreted as a file name
String fileName = httpQueryString.replaceFirst("/", "");
fileName = URLDecoder.decode(fileName);
if (new File(fileName).isFile()){
sendResponse(200, fileName, true);
}
else {
sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
}
}
}
else sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {
String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
FileInputStream fin = null;
if (statusCode == 200)
statusLine = "HTTP/1.1 200 OK" + "\r\n";
else
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
if (isFile) {
fileName = responseString;
fin = new FileInputStream(fileName);
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
contentTypeLine = "Content-Type: \r\n";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.HTML_END;
contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
}
outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");
if (isFile) sendFile(fin, outToClient);
else outToClient.writeBytes(responseString);
outToClient.close();
}
public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
byte[] buffer = new byte[1024] ;
int bytesRead;
while ((bytesRead = fin.read(buffer)) != -1 ) {
out.write(buffer, 0, bytesRead);
}
fin.close();
}
public static void main (String args[]) throws Exception {
ServerSocket Server = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println ("TCPServer Waiting for client on port 5000");
while(true) {
Socket connected = Server.accept();
(new myHTTPServer(connected)).start();
}
}
}
Enjoy!
You need to need to set the PrintWriter to autoflush when it prints.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
should be
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
The line terminator in HTTP is \r\n. This means that you shouldn't use println(), you should use print() and add an explicit \r\n yourself to each line.
The result of an HTTP GET is supposed to be an HTML document, not a fragment. Browsers are entitled to ignore or complain. Send this:
<html>
<head/>
<body>
<p> Hello world </p>
</body>
</html>
in my computer, at least to get the socket's inputStream:
clientSocket.getInputStream();
with out this line, sometimes chrome doesn't work
you need read the input from socket first
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line = "";
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
if(line.isEmpty())
break;
}
You should accept the request sent by client(browser in this case),to do that just add the following lines:
Buffered reader in = new Buffered reader(new InputStreamReader(client_socket.getInputStream()));
Note: you need to replace the "client_socket" part with name of your own socket for the client.
Why we need to accept browser request?
It's because if we don't accept the request browser doesn't get any acknowledgement from the server that the request that was sent is received,hence it thinks the server is not reachable any more.
My code:
public class Help {
public static void main(String args) throws IOException{
ServerSocket servsock new serverSocket(80)
Socket cs servsock, accept();
Printwriter out new Printwriter(Cs.getoutputstream), true)
BufferedReader in new BufferedReader(new InputStreamReader(cs.getInputStream());
out.println("<html> <body> <p>My first StackOverflow answer </p> </body> </html>");
out.close();
servsock.close();
}
}
You need to send
"HTTP/1.1 200 OK" first. followed by a newline
then "Content-Type: text/html; charset: UTF-8" followed by 2 newlines.
then send the HTML source for it to display as a styled webpage and not just a text output.
I used OutputStreamWriter
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
osw.write("HTTP/1.1 200 OK\nContent-Type: text/html; charset=UTF-8\n\n");
osw.write("<html><head><title>Hello World</title></head><body></body><p>Hello World</p></body></html>");
Not sending "HTTP/1.1 200 OK" first results in source code being displayed without html parsing..
And to avoid "Connection being reset" error, you need to close your socket. Very Important !!
The whole code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServer
{
ServerSocket serverSocket;
Socket socket;
FileReader fr;
OutputStreamWriter osw;
WebServer() throws IOException
{
serverSocket = new ServerSocket(8080);
socket = serverSocket.accept();
fr = new FileReader("index.html");
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write("HTTP/1.1 200 OK\nContent-Type: text/html; charset=UTF-8\n\n");
int c;
char[] ch = new char[4096];
while ((c = fr.read(ch)) != -1)
{
osw.write(ch, 0, c);
}
osw.close();
socket.close();
}
public static void main(String[] args) throws IOException
{
new WebServer();
}
}

HttpRequest in Java: Always goes to 404

I wrote this HttpRequest method, but for some reason it always goes to 404 Not Found, even though the file location exists when the java process isn't running.
import java.io.*;
import java.net.*;
import java.util.*;
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
return "image/jpeg";
}
if(fileName.endsWith(".gif")) {
return "image/gif";
}
return "application/octet-stream";
}
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message.
String requestLine = new String(br.readLine());
// Display the request line.
System.out.println();
System.out.println(requestLine);
// Get and display the header lines.
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "200 OK" + CRLF;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else {
statusLine = "404 NOT FOUND" + CRLF;
contentTypeLine = "Content Not Found!" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes("File DNE: Content Not Found!");
}
// Close streams and socket.
os.close();
br.close();
socket.close();
}
}
Any help would be greatly appreciated...I feel like it's something simple I'm missing.
I ran your code; it works fine (except for some minor issues with not printing the headers correctly, which every browser I've tried is willing to completely ignore).
Are you sure your working directory is where you expect? Try changing the 404 message to something like:
contentTypeLine = "Content Not Found: " + new File(fileName).getAbsolutePath() + CRLF;
For reference, I ran it with a test harness of:
public static void main(String[] args) throws Exception {
final ServerSocket ss = new ServerSocket(8080);
while (true)
new HttpRequest(ss.accept()).run();
}

Categories